SlideShare a Scribd company logo
1 of 30
Exception Handling
• What is Exception
• Exception and Error
Throwable
Exception Error
EXCEPTION HANDLING
• It is common to make mistakes while developing as well as
typing a program.
• A mistake might lead to an error causing the program to
produce unexpected results.
• Errors are the wrong that can make a program go wrong.
• An error may produce an incorrect output or may terminate
the execution of the program abruptly or even may cause
the system to crash.
• It is therefore important to detect and manage properly all
the possible error conditions in the program so that the
program will not terminate or crash during execution.
• There are two types of errors:
Compile-time errors
Run-time errors
Compile-time errors:
• The compile-time errors are detected and
displayed by the Java compiler, during the
compilation of the program.
• If a program contains compile-time errors,
the compiler does not create the .class file.
• So, it is necessary to fix all the errors.
• After fixing the errors, the program has to be
recompiled.
Run-time errors:
• Sometimes, a program may compile successfully
creating the .class file but may not run properly.
• Such programs may produce wrong results due to
wrong logic or may terminate due to errors such
as stack overflow.
• Such errors are called as the run-time errors.
• Exception is an abnormal condition that arises in
a code sequence at run time.
• In other words, an exception is a run-time error.
Some of the common exceptions are:
• Dividing an integer by zero.
• Accessing an element that is out of the bounds of an array.
• Trying to store a value into an array of an incompatible class or type
• Trying to cast an instance of a class to one of its subclasses.
• Passing a parameter that is not in a valid range or value for a
method.
• Attempting to use a negative size for an array.
• Accessing a character that is out of bounds of a string.
• Converting invalid string to a number.
Example:
// This program illustrates the run-time errors
class Error_Runtime
{
public static void main(String args[ ])
{
int i = 10 ;
int j = 2 ;
int k = i/(j-j); // Division by zero
System.out.println("n k = " + k);
int l = i/(j+j);
System.out.println("n l = " + l);
}
}
The above program is syntactically correct and therefore does not
produce any error during compilation.
However, when the program is run, it displays the following message
and stops without executing further statements.
Division by zero
Exceptions
• An exception is a run-time error.
• When the Java interpreter encounters an error such as dividing
an integer by zero, it creates an exception object and throws it
(informs that an error has occurred).
• If the exception object is not caught and handled properly, the
interpreter will display an error message and will terminate the
program.
• If one wants the program to continue with the execution of the
remaining code, then one should try to catch the exception object
thrown by the error condition and then display an appropriate
message for taking corrective action. The task is known as
exception handling.
• The purpose of exception handling mechanism is to provide a
means to detect and report an exceptional circumstance so that
appropriate action can be taken.
• Java exception handling is managed via five keywords: try,
catch, throw, throws and finally.
• The error handling code basically consists of two segments; one
to detect errors and to throw exceptions and the other to catch
exceptions and to take appropriate actions.
Java Exceptions: Some of the common exceptions are listed
in the following table:
Exception Meaning
ArithmeticException Arithmetic error, such as divide by zero.
ArrayIndexOutOfBoundsException Array index is out of bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
FileNotFoundException Attempt to access a nonexistent file.
IOException Caused by general I/O failures, such as
inability to read from a file.
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings
and number fails.
OutOfMemoryException Caused when there is not enough memory
to allocate a new object
StringIndexOutOfBoundsException Caused when a program attempts to
access a nonexistent character position in a
string.
SerurityException Caused when an applet tries to perform an
action not allowed by the browser’s security
setting.
StackOverflowException Caused when the system runs out of the
stack space.
Syntax of Exception Handling Code: The basic concept of
exception handling is throwing an exception and catching it.
try block
Statement that causes an
exception
catch block
Statement that handles the
exception
Throws exception
object Exception object creator
Exception handling mechanism
Cont.
• Java uses a keyword try to preface a block of code that is likely to cause an
error condition and throw an exception.
• A catch block defined by the keyword catch catches the exception thrown by the
try block and handles it appropriately.
• The catch block is added immediately after the try block.
• The general form of exception handling block is:
try
{
// Block of code to monitor for errors
}
catch(Exception-type1 exOb)
{ // Exception handler for Exception Type1 }
catch(Exception-type2 exOb)
{ // Exception handler for Exception Type2 }
…………….
…………….
finally
{ // Block of code to be executed before try block ends }
• Here, Exception-type is the type of exception that has occurred.
Now consider the following program, that illustrates the use
of the try and catch to handle exception.
// This program illustrates the use of the try and catch for exception handling
class TryCatch
{
public static void main(String args[ ])
{
int i = 10 ;
int j = 2 ;
int k, l ;
try
{
k = i / ( j – j ); // Exception
}
catch(ArithmeticException e) // Exception will be caught here
{
System.out.println("n Division by zero");
}
l = i/(j+j);
System.out.println (" l = " + l);
}
}
Cont.
• The above program displays the following output:
• Division by zero
• l = 2
• Note that the above program didn’t stop at the point of
exceptional condition.
• It catches the error condition, prints the error message,
and then continues the execution, as if nothing has
happened.
• Notice that the previous program did not display the
value of l.
Now, consider an another program of exception handling in which the try….catch
block catches the invalid entries in the list of the command line arguments.
class Number_Format_Exception
{
public static void main(String args[])
{
int invalid = 0;
int n, count = 0;
for(int i = 0; i < args.length; i++)
{
try
{
n = Integer.parseInt(args[i]);
}
catch (NumberFormatException e)
{
invalid = invalid + 1 ;
System.out.println("n Invalid Number: " + args[i]);
}
count = count + 1 ;
}
System.out.println("n Valid Numbers = " + count);
System.out.println("n Invalid Numbers = " + invalid);
}
}
javac Number_Format_Exception.java
java Number_Format_Exception 10 10.75 50 C++ 50.5 15
Output:
Invalid Number: 10.75
Invalid Number: C++
Invalid Number: 50.5
Valid Numbers = 3
Invalid Numbers = 3
Multiple catch statements:
• It is also possible to have more than one catch statement
in the catch block.
• When an exception in a try block is generated, the Java
treats the multiple catch statements like cases in a switch
statement.
• The first statement whose parameter matches with the
exception object will be executed, and the remaining
statements will be skipped.
• Note that Java does not require any processing of the
exception at all. One can simply have a catch statement
with an empty block to avoid abortion, as shown below:
catch (Exception e) ;
• The catch statement simply ends with a semicolon, which
does nothing. This statement will catch an exception and
then ignore it.
Example:
// This program illustrates the use of the multiple catch statements
class Multiple_Catch
{
public static void main(String args[])
{
try
{
int a = args.length ;
System.out.println(" a = " + a);
int b = 42 / a ;
int c[ ] = {1};
c[42] = 99 ;
}
catch(ArithmeticException e)
{ System.out.println("n Divide by zero " + e); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(" Array index out of bounds " + e); }
System.out.println(" After the try/catch blocks");
}
}
Use of the finally statement:
• finally statement is used to handle an exception
that is not caught by any of the previous catch
statements.
• finally block can be used to handle any exception
generated within a try block.
• It may be added immediately after the try block or
after the last catch block.
• When a finally block is defined, this is guaranteed
to execute, regardless of whether or not an
exception is thrown.
• The following program illustrates the use of the
finally statement.
Example:
// This program illustrates the use of the multiple catch statements
class Finally_Class
{ // Throwing an exception out of the method
static void method1( )
{
try
{
System.out.println("n Inside method1");
throw new RuntimeException("Example");
}
finally
{ System.out.println("tfinally block of method1"); }
}
// Return from within a try block
static void method2( )
{
try
{
System.out.println("n Inside method2");
return ;
}
finally
{ System.out.println("tfinally block of method2"); }
}
Cont.
// Execute the try block normally
static void method3( )
{
try
{
System.out.println("n Inside method3");
}
finally
{
System.out.println("tfinally block of method3");
}
}
public static void main(String args[])
{
try
{
method1( );
}
catch(Exception e)
{
System.out.println("tException caught");
}
method2( );
method3( );
}
} // End of the class definition
Output:
Inside method1
finally block of method1
Exception caught
Inside method2
finally block of method2
Inside method3
finally block of method3
Cont.
• In above program, method1( ) prematurely breaks out of
the try by throwing an exception.
•
• The finally clause is executed on the way out.
• The method2( ) of try statement is exited via a return
statement.
• The finally clause is executed before method2 returns.
• In the method3( ), the try statement executes normally,
without error.
• However, the finally block is still executed.
Throwing own exception:
• It is also possible to throw our own exceptions.
This can be done by using the keyword throw as
follows:
throw new Throwable_subclass ;
• For example:
throw new ArithmeticException( );
throw new NumberFormatException( );
Example: Program to illustrate the use of throwing an exception
import java.lang.Exception ;
class MyException extends Exception
{
MyException(String message)
{ super(message) ; }
}
class User_Exception
{
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)
{
System.out.println("n Caught my exception");
System.out.println( e.getMessage( ) );
}
finally
{ System.out.println(" I am always here"); }
}
}
Cont.
• In the above program, 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.
Difference between Throws and
Throw
• We already know we can handle exceptions using try-
catch block.
The throws does the same thing that try-catch does but
there are some cases where you would prefer throws
over try-catch.
• For example:
Lets say we have a method myMethod() that has
statements that can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch
as shown below
• public void myMethod()
{
try
{
// Statements that might throw an
exception
}
catch (ArithmeticException e)
{ // Exception handling statements }
catch (NullPointerException e) { // Exception handling
statements
}
}
Cont..
• But suppose you have several such methods
that can cause exceptions, in that case it would
be tedious to write these try-catch for each
method. The code will become unnecessary
long and will be less-readable.
• One way to overcome this problem is by using
throws like this: declare the exceptions in the
method signature using throws and handle the
exceptions where you are calling this method by
using try-catch.
public void myMethod() throws ArithmeticException, NullPointerException
{
// Statements that might throw an exception
}
public static void main(String args[])
{
try
{
myMethod();
}
catch (ArithmeticException e)
{
// Exception handling statements
}
catch (NullPointerException e)
{
// Exception handling statements
} }
import java.io.*;
class ThrowExample
{
void myMethod(int num)throws IOException, ClassNotFoundException
{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}
public class Example1
{
public static void main(String args[])
{ try
{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}
catch(Exception ex)
{
System.out.println(ex);
} } }
Cont..
• One way to overcome this problem is by using
throws like this: declare the exceptions in the method
signature using throws and handle the exceptions
where you are calling this method by using try-catch.
• Another advantage of using this approach is that you
will be forced to handle the exception when you call
this method, all the exceptions that are declared
using throws, must be handled where you are calling
this method else you will get compilation error.

More Related Content

Similar to Exception Handling Exception Handling Exception Handling

Similar to Exception Handling Exception Handling Exception Handling (20)

Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception
ExceptionException
Exception
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Recently uploaded

Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
drjose256
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
benjamincojr
 
Seizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksSeizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networks
IJECEIAES
 

Recently uploaded (20)

handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, Functions
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
 
21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Students
 
Intro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniIntro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney Uni
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility Applications
 
Seizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksSeizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networks
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
 

Exception Handling Exception Handling Exception Handling

  • 1. Exception Handling • What is Exception • Exception and Error Throwable Exception Error
  • 2. EXCEPTION HANDLING • It is common to make mistakes while developing as well as typing a program. • A mistake might lead to an error causing the program to produce unexpected results. • Errors are the wrong that can make a program go wrong. • An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. • It is therefore important to detect and manage properly all the possible error conditions in the program so that the program will not terminate or crash during execution. • There are two types of errors: Compile-time errors Run-time errors
  • 3. Compile-time errors: • The compile-time errors are detected and displayed by the Java compiler, during the compilation of the program. • If a program contains compile-time errors, the compiler does not create the .class file. • So, it is necessary to fix all the errors. • After fixing the errors, the program has to be recompiled.
  • 4. Run-time errors: • Sometimes, a program may compile successfully creating the .class file but may not run properly. • Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. • Such errors are called as the run-time errors. • Exception is an abnormal condition that arises in a code sequence at run time. • In other words, an exception is a run-time error.
  • 5. Some of the common exceptions are: • Dividing an integer by zero. • Accessing an element that is out of the bounds of an array. • Trying to store a value into an array of an incompatible class or type • Trying to cast an instance of a class to one of its subclasses. • Passing a parameter that is not in a valid range or value for a method. • Attempting to use a negative size for an array. • Accessing a character that is out of bounds of a string. • Converting invalid string to a number.
  • 6. Example: // This program illustrates the run-time errors class Error_Runtime { public static void main(String args[ ]) { int i = 10 ; int j = 2 ; int k = i/(j-j); // Division by zero System.out.println("n k = " + k); int l = i/(j+j); System.out.println("n l = " + l); } } The above program is syntactically correct and therefore does not produce any error during compilation. However, when the program is run, it displays the following message and stops without executing further statements. Division by zero
  • 7. Exceptions • An exception is a run-time error. • When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it (informs that an error has occurred). • If the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program. • If one wants the program to continue with the execution of the remaining code, then one should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective action. The task is known as exception handling. • The purpose of exception handling mechanism is to provide a means to detect and report an exceptional circumstance so that appropriate action can be taken. • Java exception handling is managed via five keywords: try, catch, throw, throws and finally. • The error handling code basically consists of two segments; one to detect errors and to throw exceptions and the other to catch exceptions and to take appropriate actions.
  • 8. Java Exceptions: Some of the common exceptions are listed in the following table: Exception Meaning ArithmeticException Arithmetic error, such as divide by zero. ArrayIndexOutOfBoundsException Array index is out of bounds. ArrayStoreException Assignment to an array element of an incompatible type. FileNotFoundException Attempt to access a nonexistent file. IOException Caused by general I/O failures, such as inability to read from a file. NullPointerException Caused by referencing a null object NumberFormatException Caused when a conversion between strings and number fails. OutOfMemoryException Caused when there is not enough memory to allocate a new object StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character position in a string. SerurityException Caused when an applet tries to perform an action not allowed by the browser’s security setting. StackOverflowException Caused when the system runs out of the stack space.
  • 9. Syntax of Exception Handling Code: The basic concept of exception handling is throwing an exception and catching it. try block Statement that causes an exception catch block Statement that handles the exception Throws exception object Exception object creator Exception handling mechanism
  • 10. Cont. • Java uses a keyword try to preface a block of code that is likely to cause an error condition and throw an exception. • A catch block defined by the keyword catch catches the exception thrown by the try block and handles it appropriately. • The catch block is added immediately after the try block. • The general form of exception handling block is: try { // Block of code to monitor for errors } catch(Exception-type1 exOb) { // Exception handler for Exception Type1 } catch(Exception-type2 exOb) { // Exception handler for Exception Type2 } ……………. ……………. finally { // Block of code to be executed before try block ends } • Here, Exception-type is the type of exception that has occurred.
  • 11. Now consider the following program, that illustrates the use of the try and catch to handle exception. // This program illustrates the use of the try and catch for exception handling class TryCatch { public static void main(String args[ ]) { int i = 10 ; int j = 2 ; int k, l ; try { k = i / ( j – j ); // Exception } catch(ArithmeticException e) // Exception will be caught here { System.out.println("n Division by zero"); } l = i/(j+j); System.out.println (" l = " + l); } }
  • 12. Cont. • The above program displays the following output: • Division by zero • l = 2 • Note that the above program didn’t stop at the point of exceptional condition. • It catches the error condition, prints the error message, and then continues the execution, as if nothing has happened. • Notice that the previous program did not display the value of l.
  • 13. Now, consider an another program of exception handling in which the try….catch block catches the invalid entries in the list of the command line arguments. class Number_Format_Exception { public static void main(String args[]) { int invalid = 0; int n, count = 0; for(int i = 0; i < args.length; i++) { try { n = Integer.parseInt(args[i]); } catch (NumberFormatException e) { invalid = invalid + 1 ; System.out.println("n Invalid Number: " + args[i]); } count = count + 1 ; } System.out.println("n Valid Numbers = " + count); System.out.println("n Invalid Numbers = " + invalid); } }
  • 14. javac Number_Format_Exception.java java Number_Format_Exception 10 10.75 50 C++ 50.5 15 Output: Invalid Number: 10.75 Invalid Number: C++ Invalid Number: 50.5 Valid Numbers = 3 Invalid Numbers = 3
  • 15. Multiple catch statements: • It is also possible to have more than one catch statement in the catch block. • When an exception in a try block is generated, the Java treats the multiple catch statements like cases in a switch statement. • The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped. • Note that Java does not require any processing of the exception at all. One can simply have a catch statement with an empty block to avoid abortion, as shown below: catch (Exception e) ; • The catch statement simply ends with a semicolon, which does nothing. This statement will catch an exception and then ignore it.
  • 16. Example: // This program illustrates the use of the multiple catch statements class Multiple_Catch { public static void main(String args[]) { try { int a = args.length ; System.out.println(" a = " + a); int b = 42 / a ; int c[ ] = {1}; c[42] = 99 ; } catch(ArithmeticException e) { System.out.println("n Divide by zero " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(" Array index out of bounds " + e); } System.out.println(" After the try/catch blocks"); } }
  • 17. Use of the finally statement: • finally statement is used to handle an exception that is not caught by any of the previous catch statements. • finally block can be used to handle any exception generated within a try block. • It may be added immediately after the try block or after the last catch block. • When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown. • The following program illustrates the use of the finally statement.
  • 18. Example: // This program illustrates the use of the multiple catch statements class Finally_Class { // Throwing an exception out of the method static void method1( ) { try { System.out.println("n Inside method1"); throw new RuntimeException("Example"); } finally { System.out.println("tfinally block of method1"); } } // Return from within a try block static void method2( ) { try { System.out.println("n Inside method2"); return ; } finally { System.out.println("tfinally block of method2"); } }
  • 19. Cont. // Execute the try block normally static void method3( ) { try { System.out.println("n Inside method3"); } finally { System.out.println("tfinally block of method3"); } } public static void main(String args[]) { try { method1( ); } catch(Exception e) { System.out.println("tException caught"); } method2( ); method3( ); } } // End of the class definition
  • 20. Output: Inside method1 finally block of method1 Exception caught Inside method2 finally block of method2 Inside method3 finally block of method3
  • 21. Cont. • In above program, method1( ) prematurely breaks out of the try by throwing an exception. • • The finally clause is executed on the way out. • The method2( ) of try statement is exited via a return statement. • The finally clause is executed before method2 returns. • In the method3( ), the try statement executes normally, without error. • However, the finally block is still executed.
  • 22. Throwing own exception: • It is also possible to throw our own exceptions. This can be done by using the keyword throw as follows: throw new Throwable_subclass ; • For example: throw new ArithmeticException( ); throw new NumberFormatException( );
  • 23. Example: Program to illustrate the use of throwing an exception import java.lang.Exception ; class MyException extends Exception { MyException(String message) { super(message) ; } } class User_Exception { 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) { System.out.println("n Caught my exception"); System.out.println( e.getMessage( ) ); } finally { System.out.println(" I am always here"); } } }
  • 24. Cont. • In the above program, 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.
  • 25. Difference between Throws and Throw • We already know we can handle exceptions using try- catch block. The throws does the same thing that try-catch does but there are some cases where you would prefer throws over try-catch. • For example: Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below
  • 26. • public void myMethod() { try { // Statements that might throw an exception } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements } }
  • 27. Cont.. • But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable. • One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch.
  • 28. public void myMethod() throws ArithmeticException, NullPointerException { // Statements that might throw an exception } public static void main(String args[]) { try { myMethod(); } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements } }
  • 29. import java.io.*; class ThrowExample { void myMethod(int num)throws IOException, ClassNotFoundException { if(num==1) throw new IOException("IOException Occurred"); else throw new ClassNotFoundException("ClassNotFoundException"); } } public class Example1 { public static void main(String args[]) { try { ThrowExample obj=new ThrowExample(); obj.myMethod(1); } catch(Exception ex) { System.out.println(ex); } } }
  • 30. Cont.. • One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch. • Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error.