SlideShare a Scribd company logo
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 (20)

PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
PPT
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
PPTX
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
PPT
Exception
Harry Potter
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Young Alista
 
PPT
Exception
Hoang Nguyen
 
PPT
Exception
Luis Goldster
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
James Wong
 
DOCX
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
PPTX
Exception handling in java
Kavitha713564
 
PPTX
Exception handling in java
Elizabeth alexander
 
PPT
Exceptions
Soham Sengupta
 
PDF
Java unit 11
Shipra Swati
 
PPTX
Java Exceptions and Exception Handling
MaqdamYasir
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Exception
Harry Potter
 
Exception
Tony Nguyen
 
Exception
Fraboni Ec
 
Exception
Tony Nguyen
 
Exception
Young Alista
 
Exception
Hoang Nguyen
 
Exception
Luis Goldster
 
Exception
Fraboni Ec
 
Exception
James Wong
 
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Exception handling in java
Kavitha713564
 
Exception handling in java
Elizabeth alexander
 
Exceptions
Soham Sengupta
 
Java unit 11
Shipra Swati
 
Java Exceptions and Exception Handling
MaqdamYasir
 

Recently uploaded (20)

PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PPTX
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
Ad

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.