SlideShare a Scribd company logo
Chapter 12



Exception Handling


                 http://www.java2all.com
Introduction



               http://www.java2all.com
Exception is a run-time error which arises during
the execution of java program. The term exception
in java stands for an “exceptional event”.

   So Exceptions are nothing but some abnormal
and typically an event or conditions that arise
during the execution which may interrupt the
normal flow of program.

   An exception can occur for many different
reasons, including the following:

                                           http://www.java2all.com
A user has entered invalid data.
   A file that needs to be opened cannot be found.
   A network connection has been lost in the
middle of communications, or the JVM has run out
of memory.

   “If the exception object is not handled properly,
the interpreter will display the error and will
terminate the program.




                                           http://www.java2all.com
Now if we want to continue the program
with the remaining code, then we should write the part
of the program which generate the error in the try{}
block and catch the errors using catch() block.

           Exception turns the direction of normal
flow of the program control and send to the related
catch() block and should display error message for
taking proper action. This process is known as.”
Exception handling



                                             http://www.java2all.com
The purpose of exception handling is to detect
and report an exception so that proper action can be
taken and prevent the program which is automatically
terminate or stop the execution because of that
exception.
      Java exception handling is managed by using
five keywords: try, catch, throw, throws and finally.

Try:        Piece of code of your program that you
want to monitor for exceptions are contained within a
try block. If an exception occurs within the try block,
it is thrown.
Catch:      Catch block can catch this exception and
handle it in some logical manner.              http://www.java2all.com
Throw:     System-generated exceptions are
automatically thrown by the Java run-time system.
Now if we want to manually throw an exception, we
have to use the throw keyword.

Throws: If a method is capable of causing an
exception that it does not handle, it must specify this
behavior so that callers of the method can guard
themselves against that exception.

     You do this by including a throws clause in the
method’s declaration. Basically it is used for
IOException. A throws clause lists the types of
exceptions that a method might throw.          http://www.java2all.com
This is necessary for all exceptions, except those
of type Error or RuntimeException, or any of their
subclasses.

     All other exceptions that a method can throw
must be declared in the throws clause. If they are not,
a compile-time error will result.

Finally: Any code that absolutely must be executed
before a method returns, is put in a finally block.

General form:

                                              http://www.java2all.com
try {
        // block of code to monitor for errors
}
catch (ExceptionType1 e1) {
       // exception handler for ExceptionType1
}
catch (ExceptionType2 e2) {
       // exception handler for ExceptionType2
}
// ...
finally {
       // block of code to be executed before try block
ends
}                                            http://www.java2all.com
Exception Hierarchy:




                       http://www.java2all.com
All exception classes are subtypes of the
java.lang.Exception class.

      The exception class is a subclass of the
Throwable class. Other than the exception class there
is another subclass called Error which is derived from
the Throwable class.

Errors :
      These are not normally trapped form the Java
programs.
Errors are typically ignored in your code because you
can rarely do anything about an error.
                                             http://www.java2all.com
These conditions normally happen in case of
severe failures, which are not handled by the java
programs. Errors are generated to indicate errors
generated by the runtime environment.

For Example :

(1) JVM is out of Memory. Normally programs
cannot recover from errors.

(2) If a stack overflow occurs then an error will
arise. They are also ignored at the time of
compilation.
                                            http://www.java2all.com
The Exception class has two main subclasses:

(1) IOException or Checked Exceptions class and

(2) RuntimeException or Unchecked Exception class

(1) IOException or Checked Exceptions :

      Exceptions that must be included in a method’s
throws list if that method can generate one of these
exceptions and does not handle it itself. These are
called checked exceptions.
                                           http://www.java2all.com
For example, if a file is to be opened, but the file
cannot be found, an exception occurs.

      These exceptions cannot simply be ignored at
the time of compilation.

     Java’s Checked Exceptions Defined in java.lang



                                              http://www.java2all.com
Exception                 Meaning

ClassNotFoundException    Class not found.

CloneNotSupportedExcept Attempt to clone an object that does not
ion                     implement the Cloneable interface.

IllegalAccessException    Access to a class is denied.

                          Attempt to create an object of an
InstantiationException
                          abstract class or interface.

Exception                 Meaning

ClassNotFoundException    Class not found.

CloneNotSupportedExcept Attempt to clone an object that does not
ion                     implement the Cloneable interface.

                                                              http://www.java2all.com
One thread has been interrupted by
InterruptedException
                        another thread.

NoSuchFieldException    A requested field does not exist.

NoSuchMethodException   A requested method does not exist.




                                                             http://www.java2all.com
(2) RuntimeException or Unchecked Exception :

     Exceptions need not be included in any method’s
throws list. These are called unchecked exceptions
because the compiler does not check to see if a method
handles or throws these exceptions.

     As opposed to checked exceptions, runtime
exceptions are ignored at the time of compilation.

Java’s Unchecked RuntimeException Subclasses


                                             http://www.java2all.com
Exception                      Meaning

                               Arithmetic error, such as
ArithmeticException
                               divide-by-zero.
ArrayIndexOutOfBoundsExcept
                            Array index is out-of-bounds.
ion
                               Assignment to an array element of an
ArrayStoreException
                               incompatible type.

ClassCastException             Invalid cast.

                               Illegal monitor operation, such as
IllegalMonitorStateException
                               waiting on an unlocked thread.
                               Environment or application is in
IllegalStateException
                               incorrect state.
                               Requested operation not compatible
IllegalThreadStateException
                               with current thread state.   http://www.java2all.com
IndexOutOfBoundsException       Some type of index is out-of-bounds.


NegativeArraySizeException      Array created with a negative size.


NullPointerException            Invalid use of a null reference.

                                Invalid conversion of a string to a
NumberFormatException
                                numeric format.

SecurityException               Attempt to violate security.

                                Attempt to index outside the bounds of
StringIndexOutOfBounds
                                a string.

                                An unsupported operation was
UnsupportedOperationException
                                encountered.
                                                               http://www.java2all.com
Try And Catch



                http://www.java2all.com
We have already seen introduction about try and
catch block in java exception handling.

Now here is the some examples of try and catch block.

EX :
public class TC_Demo
{
                                               Output :
  public static void main(String[] args)
  {
    int a=10;       int b=5,c=5;    int x,y;   Divide by zero
    try {
       x = a / (b-c);
                                               y=1
    }
    catch(ArithmeticException e){
       System.out.println("Divide by zero");
    }
    y = a / (b+c);
    System.out.println("y = " + y);

  }       }
                                                                http://www.java2all.com
Note that program did not stop at the point of
exceptional condition.It catches the error condition,
prints the error message, and continues the execution,
as if nothing has happened.

      If we run same program without try catch block
we will not gate the y value in output. It displays the
following message and stops without executing further
statements.

     Exception in thread "main"
     java.lang.ArithmeticException: / by zero
at Thrw_Excp.TC_Demo.main(TC_Demo.java:10)
                                             http://www.java2all.com
Here we write ArithmaticException in catch
block because it caused by math errors such as divide
by zero.

Now how to display description of an exception ?

      You can display the description of thrown object
by using it in a println() statement by simply passing
the exception as an argument. For example;

catch (ArithmeticException e)
{
       system.out.pritnln(“Exception:” +e);
}                                        http://www.java2all.com
Multiple catch blocks :
     It is possible to have multiple catch blocks in our
program.
EX :
public class MultiCatch
{
  public static void main(String[] args)
  {
    int a [] = {5,10}; int b=5;
    try      {
                                                      Output :
       int x = a[2] / b - a[1];
    }
    catch(ArithmeticException e)       {              Array index error
       System.out.println("Divide by zero");
    }
                                                      y=2
    catch(ArrayIndexOutOfBoundsException e)       {
       System.out.println("Array index error");
    }
    catch(ArrayStoreException e)        {
       System.out.println("Wrong data type");
    }
    int y = a[1]/a[0];
    System.out.println("y = " + y);
  }        }                                                         http://www.java2all.com
Note that array element a[2] does not exist.
Therefore the index 2 is outside the array boundry.

      When exception in try block is generated, the
java treats the multiple catch statements like cases in
switch statement.

      The first statement whose parameter matches
with the exception object will be executed, and the
remaining statements will be skipped.

     When you are using multiple catch blocks, it is
important to remember that exception subclasses must
come before any of their superclasses.     http://www.java2all.com
This is because a catch statement that uses a
superclass will catch exceptions of that type plus any
of its subclasses.

     Thus, a subclass will never be reached if it
comes after its superclass. And it will result into
syntax error.

// Catching super exception before sub

EX :


                                               http://www.java2all.com
class etion3
{
   public static void main(String args[])
   {
     int num1 = 100;
     int num2 = 50;
     int num3 = 50;
     int result1;

        try
        {
          result1 = num1/(num2-num3);

        }
          System.out.println("Result1 = " + result1);   Output :
        catch (Exception e)
        {                                               Array index error
          System.out.println("This is mistake. ");
        }
                                                        y=2
        catch(ArithmeticException g)
        {
          System.out.println("Division by zero");

        }
    }
}

                                                                       http://www.java2all.com
Output :
      If you try to compile this program, you will
receive an error message because the exception has
already been caught in first catch block.

     Since ArithmeticException is a subclass of
Exception, the first catch block will handle all
exception based errors,

      including ArithmeticException. This means that
the second catch statement will never execute.

      To fix the problem, revere the order of the catch
statement.                                     http://www.java2all.com
Nested try statements :

     The try statement can be nested.

     That is, a try statement can be inside a block of
another try.

     Each time a try statement is entered, its
corresponding catch block has to entered.

     The catch statements are operated from
corresponding statement blocks defined by try.

                                                 http://www.java2all.com
EX :
public class NestedTry
{
    public static void main(String args[])
    {
       int num1 = 100;
       int num2 = 50;
       int num3 = 50;
       int result1;
       try     {
          result1 = num1/(num2-num3);
          System.out.println("Result1 = " + result1);     Output :
          try {
            result1 = num1/(num2-num3);
            System.out.println("Result1 = " + result1);
          }                                               This is outer catch
          catch(ArithmeticException e)
          {
            System.out.println("This is inner catch");
          }
       }
       catch(ArithmeticException g)
       {
          System.out.println("This is outer catch");
       }
    }
}                                                                         http://www.java2all.com
Finally



          http://www.java2all.com
Java supports another statement known as
finally statement that can be used to handle an
exception that is not caught by any of the previous
catch statements.

       We can put finally block after the try block or
after the last catch block.

     The finally block is executed in all
circumstances. Even if a try block completes without
problems, the finally block executes.


                                               http://www.java2all.com
EX :
public class Finally_Demo
{
    public static void main(String args[])
    {
       int num1 = 100;
       int num2 = 50;
       int num3 = 50;
       int result1;

        try
        {                                               Output :
          result1 = num1/(num2-num3);
          System.out.println("Result1 = " + result1);
        }
        catch(ArithmeticException g)                    Division by zero
        {
          System.out.println("Division by zero");
                                                        This is final
        }
        finally
        {
           System.out.println("This is final");
        }
    }
}
                                                                       http://www.java2all.com
Throw



        http://www.java2all.com
We saw that an exception was generated by the
JVM when certain run-time problems occurred.
It is also possible for our program to explicitly
generate an exception.

     This can be done with a throw statement. Its
form is as follows:

Throw object;

     Inside a catch block, you can throw the same
exception object that was provided as an argument.

                                            http://www.java2all.com
This can be done with the following syntax:

catch(ExceptionType object)
{
       throw object;
}

     Alternatively, you may create and throw a new
exception object as follows:

       Throw new ExceptionType(args);


                                           http://www.java2all.com
Here, exceptionType is the type of the exception
object and args is the optional argument list for its
constructor.

      When a throw statement is encountered, a search
for a matching catch block begins and if found it is
executed.

EX :
class Throw_Demo
{
   public static void a()
   {
      try
     {
        System.out.println("Before b");
        b();
      }
                                            http://www.java2all.com
catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here
 {
       System.out.println("J : " + j) ;
  }
}
public static void b()
  {
    int a=5,b=0;
    try
    { System.out.println("We r in b");
       System.out.println("********");

             int x = a/b;
      }
      catch(ArithmeticException e)
      {
        System.out.println("c : " + e);
        throw new ArrayIndexOutOfBoundsException("demo"); //throw from here
      }
  }




                                                                                 http://www.java2all.com
public static void main(String args[])
     {
                                                        Output :
         try
         {
           System.out.println("Before a");              Before a
           a();
           System.out.println("********");              Before b
           System.out.println("After a");
         }
                                                        We r in b
         catch(ArithmeticException e)
         {
                                                        ********
           System.out.println("Main Program : " + e);   c:
         }
     }                                                  java.lang.ArithmeticExcepti
}
                                                        on: / by zero
                                                        J:
                                                        java.lang.ArrayIndexOutOf
                                                        BoundsException: demo
                                                        ********

                                                        After a
                                                                          http://www.java2all.com
Throwing our own object :

      If we want to throw our own exception, we can
do this by using the keyword throw as follow.

         throw new Throwable_subclass;

Example : throw new ArithmaticException( );
         throw new NumberFormatException( );
EX :
import java.lang.Exception;
class MyException extends Exception
{
   MyException(String message)
   { super(message);

    }
}                                          http://www.java2all.com
class TestMyException
{
   public static void main(String[] args)
   {
     int x = 5, y = 1000;
     try
     {
        float z = (float)x / (float)y;
        if(z < 0.01)
        {
           throw new MyException("Number is too small");
        }
     }
     catch(MyException e)
     {
                                                 Output :
        System.out.println("Caught MyException");
        System.out.println(e.getMessage());
     }                                           Caught MyException
     finally
     {
                                                 Number is too small
     }
        System.out.println("java2all.com");      java2all.com
   }
}



                                                                  http://www.java2all.com
Here The object e which contains the error
message "Number is too small" is caught by the catch
block which then displays the message using
getMessage( ) method.

NOTE:

      Exception is a subclass of Throwable and
therefore MyException is a subclass of
Throwable class. An object of a class that extends
Throwable can be thrown and caught.


                                             http://www.java2all.com
Throws



         http://www.java2all.com
If a method is capable of causing an exception
that it does not handle,it must specify this behavior so
that callers of the method can guard themselves
against that exception.

    You do this by including a throws clause in the
method’s declaration. Basically it is used for
IOException.

     A throws clause lists the types of exceptions that
a method might throw. This is necessary for all
exceptions, except those of type Error or
RuntimeException,or any of their subclasses.
                                              http://www.java2all.com
All other exceptions that a method can throw
must be declared in the throws clause.

      If they are not, a compile-time error will result.
This is the general form of a method declaration that
includes a throws clause:

      type method-name(parameter-list) throws
exception-list
{
// body of method
}

                                               http://www.java2all.com
Here, exception-list is a comma-separated list of
the exceptions that a method can throw.

     Throw is used to actually throw the exception,
whereas throws is declarative statement for the
method. They are not interchangeable.

EX :
class NewException extends Exception
{
   public String toS()
   {
     return "You are in NewException ";
   }
}




                                             http://www.java2all.com
class customexception
{                                                   Output :
   public static void main(String args[])
   {
      try
      {                                             ****No Problem.****
         doWork(3);
         doWork(2);
                                                    ****No Problem.****
         doWork(1);                                 ****No Problem.****
         doWork(0);
      }                                             Exception : You are in
      catch (NewException e)
      {                                             NewException
         System.out.println("Exception : " + e.toS());
      }
   }
   static void doWork(int value) throws NewException
   {
      if (value == 0)
      {
         throw new NewException();
      }
      else
      {
         System.out.println("****No Problem.****");
      }
   }
}                                                                     http://www.java2all.com

More Related Content

What's hot (20)

Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
Madishetty Prathibha
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
Md.Al-imran Roton
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
Md.Al-imran Roton
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 

Viewers also liked (8)

Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Coeducation
CoeducationCoeducation
Coeducation
skmaken
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Effects of TECHNOLOGY
Effects of TECHNOLOGYEffects of TECHNOLOGY
Effects of TECHNOLOGY
Amna Kazim
 
Impact of Fast Food
Impact of Fast FoodImpact of Fast Food
Impact of Fast Food
Manpreet Singh Bedi
 
Corruption in pakistan
Corruption in pakistan Corruption in pakistan
Corruption in pakistan
Riaz Gul Sheikh
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Coeducation
CoeducationCoeducation
Coeducation
skmaken
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Effects of TECHNOLOGY
Effects of TECHNOLOGYEffects of TECHNOLOGY
Effects of TECHNOLOGY
Amna Kazim
 
Ad

Similar to Java Exception handling (20)

Exeption handling
Exeption handlingExeption handling
Exeption handling
baabtra.com - No. 1 supplier of quality freshers
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
Fraz Bakhsh
 
Exception Handling in java masters of computer application
Exception Handling in java masters of computer applicationException Handling in java masters of computer application
Exception Handling in java masters of computer application
xidileh999
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
Java Programming
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
RanjithaM32
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
Pramod Yadav
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptxusing Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling in java masters of computer application
Exception Handling in java masters of computer applicationException Handling in java masters of computer application
Exception Handling in java masters of computer application
xidileh999
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
Java Programming
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
RanjithaM32
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
Pramod Yadav
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptxusing Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Ad

More from kamal kotecha (20)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
kamal kotecha
 
Java rmi
Java rmiJava rmi
Java rmi
kamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
kamal kotecha
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
kamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
kamal kotecha
 
Jsp element
Jsp elementJsp element
Jsp element
kamal kotecha
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
kamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Control statements
Control statementsControl statements
Control statements
kamal kotecha
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
kamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
kamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
kamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 

Recently uploaded (20)

THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation SamplerLDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptxSPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptxPEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation SamplerLDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptxSPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptxPEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 

Java Exception handling

  • 1. Chapter 12 Exception Handling http://www.java2all.com
  • 2. Introduction http://www.java2all.com
  • 3. Exception is a run-time error which arises during the execution of java program. The term exception in java stands for an “exceptional event”. So Exceptions are nothing but some abnormal and typically an event or conditions that arise during the execution which may interrupt the normal flow of program. An exception can occur for many different reasons, including the following: http://www.java2all.com
  • 4. A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory. “If the exception object is not handled properly, the interpreter will display the error and will terminate the program. http://www.java2all.com
  • 5. Now if we want to continue the program with the remaining code, then we should write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block and should display error message for taking proper action. This process is known as.” Exception handling http://www.java2all.com
  • 6. The purpose of exception handling is to detect and report an exception so that proper action can be taken and prevent the program which is automatically terminate or stop the execution because of that exception. Java exception handling is managed by using five keywords: try, catch, throw, throws and finally. Try: Piece of code of your program that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Catch: Catch block can catch this exception and handle it in some logical manner. http://www.java2all.com
  • 7. Throw: System-generated exceptions are automatically thrown by the Java run-time system. Now if we want to manually throw an exception, we have to use the throw keyword. Throws: If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. Basically it is used for IOException. A throws clause lists the types of exceptions that a method might throw. http://www.java2all.com
  • 8. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. Finally: Any code that absolutely must be executed before a method returns, is put in a finally block. General form: http://www.java2all.com
  • 9. try { // block of code to monitor for errors } catch (ExceptionType1 e1) { // exception handler for ExceptionType1 } catch (ExceptionType2 e2) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends } http://www.java2all.com
  • 10. Exception Hierarchy: http://www.java2all.com
  • 11. All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors : These are not normally trapped form the Java programs. Errors are typically ignored in your code because you can rarely do anything about an error. http://www.java2all.com
  • 12. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. For Example : (1) JVM is out of Memory. Normally programs cannot recover from errors. (2) If a stack overflow occurs then an error will arise. They are also ignored at the time of compilation. http://www.java2all.com
  • 13. The Exception class has two main subclasses: (1) IOException or Checked Exceptions class and (2) RuntimeException or Unchecked Exception class (1) IOException or Checked Exceptions : Exceptions that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. http://www.java2all.com
  • 14. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Java’s Checked Exceptions Defined in java.lang http://www.java2all.com
  • 15. Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedExcept Attempt to clone an object that does not ion implement the Cloneable interface. IllegalAccessException Access to a class is denied. Attempt to create an object of an InstantiationException abstract class or interface. Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedExcept Attempt to clone an object that does not ion implement the Cloneable interface. http://www.java2all.com
  • 16. One thread has been interrupted by InterruptedException another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist. http://www.java2all.com
  • 17. (2) RuntimeException or Unchecked Exception : Exceptions need not be included in any method’s throws list. These are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Java’s Unchecked RuntimeException Subclasses http://www.java2all.com
  • 18. Exception Meaning Arithmetic error, such as ArithmeticException divide-by-zero. ArrayIndexOutOfBoundsExcept Array index is out-of-bounds. ion Assignment to an array element of an ArrayStoreException incompatible type. ClassCastException Invalid cast. Illegal monitor operation, such as IllegalMonitorStateException waiting on an unlocked thread. Environment or application is in IllegalStateException incorrect state. Requested operation not compatible IllegalThreadStateException with current thread state. http://www.java2all.com
  • 19. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size. NullPointerException Invalid use of a null reference. Invalid conversion of a string to a NumberFormatException numeric format. SecurityException Attempt to violate security. Attempt to index outside the bounds of StringIndexOutOfBounds a string. An unsupported operation was UnsupportedOperationException encountered. http://www.java2all.com
  • 20. Try And Catch http://www.java2all.com
  • 21. We have already seen introduction about try and catch block in java exception handling. Now here is the some examples of try and catch block. EX : public class TC_Demo { Output : public static void main(String[] args) { int a=10; int b=5,c=5; int x,y; Divide by zero try { x = a / (b-c); y=1 } catch(ArithmeticException e){ System.out.println("Divide by zero"); } y = a / (b+c); System.out.println("y = " + y); } } http://www.java2all.com
  • 22. Note that program did not stop at the point of exceptional condition.It catches the error condition, prints the error message, and continues the execution, as if nothing has happened. If we run same program without try catch block we will not gate the y value in output. It displays the following message and stops without executing further statements. Exception in thread "main" java.lang.ArithmeticException: / by zero at Thrw_Excp.TC_Demo.main(TC_Demo.java:10) http://www.java2all.com
  • 23. Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero. Now how to display description of an exception ? You can display the description of thrown object by using it in a println() statement by simply passing the exception as an argument. For example; catch (ArithmeticException e) { system.out.pritnln(“Exception:” +e); } http://www.java2all.com
  • 24. Multiple catch blocks : It is possible to have multiple catch blocks in our program. EX : public class MultiCatch { public static void main(String[] args) { int a [] = {5,10}; int b=5; try { Output : int x = a[2] / b - a[1]; } catch(ArithmeticException e) { Array index error System.out.println("Divide by zero"); } y=2 catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index error"); } catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a[1]/a[0]; System.out.println("y = " + y); } } http://www.java2all.com
  • 25. Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundry. When exception in try block is generated, the java treats the multiple catch statements like cases in switch statement. The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped. When you are using multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses. http://www.java2all.com
  • 26. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass will never be reached if it comes after its superclass. And it will result into syntax error. // Catching super exception before sub EX : http://www.java2all.com
  • 27. class etion3 { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); } System.out.println("Result1 = " + result1); Output : catch (Exception e) { Array index error System.out.println("This is mistake. "); } y=2 catch(ArithmeticException g) { System.out.println("Division by zero"); } } } http://www.java2all.com
  • 28. Output : If you try to compile this program, you will receive an error message because the exception has already been caught in first catch block. Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, revere the order of the catch statement. http://www.java2all.com
  • 29. Nested try statements : The try statement can be nested. That is, a try statement can be inside a block of another try. Each time a try statement is entered, its corresponding catch block has to entered. The catch statements are operated from corresponding statement blocks defined by try. http://www.java2all.com
  • 30. EX : public class NestedTry { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); Output : try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } This is outer catch catch(ArithmeticException e) { System.out.println("This is inner catch"); } } catch(ArithmeticException g) { System.out.println("This is outer catch"); } } } http://www.java2all.com
  • 31. Finally http://www.java2all.com
  • 32. Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. We can put finally block after the try block or after the last catch block. The finally block is executed in all circumstances. Even if a try block completes without problems, the finally block executes. http://www.java2all.com
  • 33. EX : public class Finally_Demo { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { Output : result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch(ArithmeticException g) Division by zero { System.out.println("Division by zero"); This is final } finally { System.out.println("This is final"); } } } http://www.java2all.com
  • 34. Throw http://www.java2all.com
  • 35. We saw that an exception was generated by the JVM when certain run-time problems occurred. It is also possible for our program to explicitly generate an exception. This can be done with a throw statement. Its form is as follows: Throw object; Inside a catch block, you can throw the same exception object that was provided as an argument. http://www.java2all.com
  • 36. This can be done with the following syntax: catch(ExceptionType object) { throw object; } Alternatively, you may create and throw a new exception object as follows: Throw new ExceptionType(args); http://www.java2all.com
  • 37. Here, exceptionType is the type of the exception object and args is the optional argument list for its constructor. When a throw statement is encountered, a search for a matching catch block begins and if found it is executed. EX : class Throw_Demo { public static void a() { try { System.out.println("Before b"); b(); } http://www.java2all.com
  • 38. catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here { System.out.println("J : " + j) ; } } public static void b() { int a=5,b=0; try { System.out.println("We r in b"); System.out.println("********"); int x = a/b; } catch(ArithmeticException e) { System.out.println("c : " + e); throw new ArrayIndexOutOfBoundsException("demo"); //throw from here } } http://www.java2all.com
  • 39. public static void main(String args[]) { Output : try { System.out.println("Before a"); Before a a(); System.out.println("********"); Before b System.out.println("After a"); } We r in b catch(ArithmeticException e) { ******** System.out.println("Main Program : " + e); c: } } java.lang.ArithmeticExcepti } on: / by zero J: java.lang.ArrayIndexOutOf BoundsException: demo ******** After a http://www.java2all.com
  • 40. Throwing our own object : If we want to throw our own exception, we can do this by using the keyword throw as follow. throw new Throwable_subclass; Example : throw new ArithmaticException( ); throw new NumberFormatException( ); EX : import java.lang.Exception; class MyException extends Exception { MyException(String message) { super(message); } } http://www.java2all.com
  • 41. class TestMyException { public static void main(String[] args) { int x = 5, y = 1000; try { float z = (float)x / (float)y; if(z < 0.01) { throw new MyException("Number is too small"); } } catch(MyException e) { Output : System.out.println("Caught MyException"); System.out.println(e.getMessage()); } Caught MyException finally { Number is too small } System.out.println("java2all.com"); java2all.com } } http://www.java2all.com
  • 42. Here The object e which contains the error message "Number is too small" is caught by the catch block which then displays the message using getMessage( ) method. NOTE: Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught. http://www.java2all.com
  • 43. Throws http://www.java2all.com
  • 44. If a method is capable of causing an exception that it does not handle,it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. Basically it is used for IOException. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException,or any of their subclasses. http://www.java2all.com
  • 45. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } http://www.java2all.com
  • 46. Here, exception-list is a comma-separated list of the exceptions that a method can throw. Throw is used to actually throw the exception, whereas throws is declarative statement for the method. They are not interchangeable. EX : class NewException extends Exception { public String toS() { return "You are in NewException "; } } http://www.java2all.com
  • 47. class customexception { Output : public static void main(String args[]) { try { ****No Problem.**** doWork(3); doWork(2); ****No Problem.**** doWork(1); ****No Problem.**** doWork(0); } Exception : You are in catch (NewException e) { NewException System.out.println("Exception : " + e.toS()); } } static void doWork(int value) throws NewException { if (value == 0) { throw new NewException(); } else { System.out.println("****No Problem.****"); } } } http://www.java2all.com