SlideShare a Scribd company logo
Exception Handling Fundamentals
‐
An exception is a problem that arises during the
execution of a program. When an Exception(un
wanted event) occurs the normal flow of the
program is disrupted and the program/Application
terminates abnormally.
Some of the reasons for an exception
• A user has entered an 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.
It is highly recommended to handle exceptions
The main objective of exception handling is graceful
termination of program.
Exception handling doesn’t mean repairing an
exception we have to provide alternative way to
continue rest of the program normally is the
concept of exception handling .
exception handling can be managed by five
keywords:
1.try,
2. catch,
3.throw,
4.throws,
5.finally.
This is the general form of an exception-handling block
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2
}
//……
finally
{ // block of code to be executed after try block ends
}
Uncaught Exceptions
Class Test
{
public static void main(String args[])
{
doStuff();
}
public static doStuff()
{
doMoreStuff();
}
public static doMoreStuff()
{ Java Runtime Stack
System.out.println(10/0);
}
}
doMoreStuff()
doStuff()
Main()
Steps to handle Uncaught Exceptions
1.Inside a method if any exception occurs the method in
which its raised is responsible to create exception object
by including the following information
1.name of exception
2.description of exception
3.location at which exception occurs(stack trace)
2.After creation of exception object method handovers
that object to the jvm.
3.Jvm will check whether the method contains any
exception handling code or not if the method doesn’t
contain exception handling code then jvm terminates
that method abnormally and removes corresponding
entry from the stack.
4. jvm identifies callers method and checks whether caller
method contains any handling code or not. If the caller
method doest contain handling code then jvm terminates
that caller method also abnormally and removes
corresponding entry from the stack this process will be
continued until the main method. if the main method also
doesn’t contain handling code then jvm terminates main
method also abnormally and removes corresponding entry
from the stack.
5.Then JVM handovers responsibility of exception handling to
default exception handler, which is the part of jvm.
6.Defaulty Exception Handler prints exception information in
the following format and terminates program abnormally.
Exception in thread in XXX : name of the exception:
Description: stack trace
Hierarchy of Exception classes
Exception
Most of the times exceptions are caused by our program and these are
recoverable.
Child classes for Exception
1.IOException
i.EOF Exception
ii.FileNotFoundException
iii.InteruptedIOException
2.SQLException
3.ServletExcetion
4.Runtime Exception
i. ArithmeticException
ii. NumberFormatException
iii. ArrayIndexOutOfBoundsException
iv.NullPointerException
5.RemoteException
6.Interuptedexception
Error
Most of the times errors are not caused by our
program and these are due to lack of system
resources. Errors are non recoverable.
Child classes for Error
1.VMError
i.StackOverFlowError
ii.OutOfMemoryError
2.AssertionError
Types of Exception
There are mainly two types of exceptions
1.Checked Exception
2.Unchecked Exception
Checked Exception:
The exceptions which are checked by compiler for smooth
execution of the program are called checked exception.
Example: FileNotFoundException, SQLException
In our program if there is chance of rising checked
exception then compulsory we should handle that
cheeked exception either by try, catch or throws key
word otherwise we will get compile time error.
Unchecked Exception
The exception which are not checked by compiler whether
programmer handling or not such type of exceptions are
called Unchecked Exception.
Example
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Note :
1.Whether it is checked or unchecked exception that
occurs at runtime only there is no chance of occurring
any exception at compile time.
2.RuntimeException and its child classes, Error and its child
classes are unchecked except these reaming are
checked.
Exception Handling Using Try Catch
It is highly recommended to handle exceptions.
The code which may raise exception is called risky code and we have to
define that code inside the try block.
And the corresponding handling code we have to define inside the catch
block.
Syntax
Try
{
Risky code
}
Catch(Exception e)
{
Handling code;
}
Example with out Try catch
Class test
{
Public static void main(String args[])
{
System.out.println(“statement1”);
System.out.println(10/0);
System.out.println(“statement3”);
}
}
Out Put:
Statement1
Exception:AE:divide by zero
Example with Try catch
Class test
{
Public static void main(String args[])
{
System.out.println(“Before Exception ”);
try
{
System.out.println(10/0);
}
Catch(ArithmeticException e)
{
System.out.println(10/2);
}
System.out.println(“After catch statement.”);
}
}
Out Put:
Statement1
5
Statement3
Control Flow in Try Catch
Try
{
Statement1
statement2
statement3
}
Catch(Exception e)
{
statement4
}
Statement5
Case1: No Exception
Out :1,2,3,5 -normal termination
Case2: if an exception raised at statement 2 and corresponding catch block
matched
Out put:1,4,5-normal termination
Case 3: if an exception raised at statement 2 and corresponding catch block
not matched
Out Put :1,-- abnormal termination
Case 4: if an exception raised at statement 4 or statement 5
Out put: Abnormal termination
Note :
1. With in the try block if any where exception raised then rest of the try block
won’t be executed even though we handled exception. Hence we have to
write only risky code into the try block.
2. In addition to try block there may be a chance of raising an exception inside
catch and finally blocks.
3. If any statement which is not part of try block and raise an exception then it
is always abnormal termination.
Methods to print Exception Information
Throwable class defines the following methods to
print Exception Information
Note : internally default exception handler will use printStackTrace to print exception
information to the console
Method Printable Format
printStackTrace() Name of the Exception : Description :
Stack Trace
toString() Name of the Exception : Description
getMessage() Description
Example
class Test
{
public static void main(String args[])
{
try
{
system.out.println(10/0);
}
catch(ArithmeticException e)
{
e.printStackTrace();
System.out.println(e.toString());
System.out.println(e.getMessage());
}
}
}
Java.lang:AE:/ by
Zero
At test.Main()
Java.lang:AE: / by
Zero
/ by Zero
Try with multiple catch blocks
The way of handling an exception is varied from exception to
exception hence for every exception type, it is highly
recommended to take separate catch block that is try with
multiple catch blocks is always possible and recommended to
use.
Example
Try
{
Risky code;
}
Catch(Exception e)
{
}
Bad programming practice
Example:
Try
{
Risky code;
}
Catch(Arithmetic Exception e)
{
Perform any Arithmetic operation;
}
Catch(FileNotFoundException e)
{
Use local file instead of remote file;
}
Catch(Exception e)
{
//Default Exception Handling;
}
Best Programming Practice
If try with multiple catch blocks present then the order of catch blocks is
very important.
We have to take child first and then parent otherwise we will get compile
time error saying
Exception XXX has already been caught
Example
Try
{
Risky code
}
Catch(Exception e)
{
}
Catch(ArithmeticException e)
{
}
Out put : Compile time error
Try
{
Risky code
}
Catch(ArithmeticException e)
{
}
Catch(Exception e)
{
}
Output:
Exception handled .
Nested try Statements
One try-catch block can be present in the another
try’s body. This is called Nesting of try catch blocks.
Each time a try block does not have a catch handler
for a particular exception, the stack is unwound and
the next try block’s catch handlers are inspected for
a match.
If no catch block matches, then the java run-time
system will handle the exception.
Syntax of Nested try Catch
.... //Main try block
try
{
statement 1;
statement 2;
//try-catch block inside another try block
try
{
statement 3;
statement 4;
}
catch(Exception e1)
{
//Exception Message
}
}
catch(Exception e3) //Catch of Main(parent) try block
{
//Exception Message
}
Throw Keyword
Some times we can create exception object explicitly and handover to jvm
manually, for this we have to use throw key word.
Throw new ArithmeticException(“/ by zero”);
The main objective of throw key word is to handover our created
exception object to jvm manually.
Example
Class test
{
Public static void main(String args[])
{
Throw new ArithmeticException(“/ by zero”);
}
}
Best use of throw keyword is for user defined exceptions or customized
exceptions.
Throws keyword
In our program if there is a possibility of raising checked exception then compulsory we
should handle that checked exception otherwise we will get compile time error saying
Unreported Exception XXX must be caught or declared to be thrown
Syntax
type method-name(parameter-list) throws exception-list
{ // body of method }
Example
Class test
{
Public static void main(String args[])
PrintWriter pw=new PrintWriter(“abc.txt”);
pw.println(“hello”);
}
}
Compile time error: Unreported Exception java.io.FileNotFound; must be caught or
declared to be thrown
We can handle this compile time error by using Throws keyword or by
using Try catch.
The purpose of throws keyword is to delegate the responsibility of
exception handling to the caller (it may be another method or JVM)
then caller method is responsible to handle that exception
Example
Class test
{
Public static void main(String args[]) throws FileNotFoundException
{
PrintWriter pw=new PrintWriter(“abc.txt”);
pw.println(“hello”);
}
}
Throws key word requires only for checked
exception.
Throws key word required only to convince
compiler and usage of throws keyword
doesn't prevent abnormal termination of the
program.
Finally block
finally block is a block that is used to execute important(clean up) code such as closing
connection, stream etc.
finally block is always executed whether exception is handled or not.
finally block follows try or catch block.
Example
Try
{
Risky code
}
Catch(Exception e)
{
}
finally
{
Clean up code;
}
Java’s Built-in Exceptions
Unchecked Exceptions
Checked Exceptions
User defined Exception subclass
We can also create our own exception sub class simply by extending java Exception class.
Example
class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{
super(s);
}
}
class CustException
{
public static void main(String args[])
{
int age=Integer.parseInt(args[0]);
if(age<18)
{
throw new TooYoungException("you are too young so u r not allowed");
}
else
{
System.out.println("u r allowed");
}
}
}
Chained Exception
Chained Exception was added to Java in JDK 1.4. This feature allow
you to relate one exception with another exception, i.e one
exception describes cause of another exception.
Two new constructors and two new methods were added to
Throwable class to support chained exception.
Throwable( Throwable cause )
Throwable( String str, Throwable cause )
getCause() and initCause() are the two methods added to
Throwable class.
getCause() method returns the actual cause associated with current
exception.
initCause() set an underlying cause(exception) with invoking
exception.
Example
import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
if(b==0)
{
ArithmeticException ae = new ArithmeticException("top layer"); ae.initCause( new IOException("cause") );
throw ae;
}
else
{
System.out.println(a/b);
}
}
public static void main(String[] args)
{
Try
{
divide(5, 0);
}
catch(ArithmeticException ae)
{
System.out.println( "caught : " +ae);
System.out.println("actual cause: "+ae.getCause());
}
}
}

More Related Content

PPT
Exceptionhandling
PPTX
Interface andexceptions
PPTX
Java exception handling
DOCX
Java Exception handling
PPTX
java exception.pptx
PPT
Exception Handling Exception Handling Exception Handling
PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPTX
Java-Exception Handling Presentation. 2024
Exceptionhandling
Interface andexceptions
Java exception handling
Java Exception handling
java exception.pptx
Exception Handling Exception Handling Exception Handling
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Java-Exception Handling Presentation. 2024

Similar to Exception‐Handling in object oriented programming (20)

PPTX
Exception Handling In Java Presentation. 2024
PPTX
Exception Handling.pptx
PPTX
using Java Exception Handling in Java.pptx
PPTX
presentation-on-exception-handling 1.pptx
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPTX
Exceptionhandling
PPT
Exceptions in java
PPTX
Exception handling in java
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
PPTX
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PDF
Java Day-5
PPTX
L14 exception handling
PDF
Class notes(week 8) on exception handling
PPTX
Z blue exception
DOCX
Exception handling in java
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Chap2 exception handling
PPT
8.Exception handling latest(MB).ppt .
Exception Handling In Java Presentation. 2024
Exception Handling.pptx
using Java Exception Handling in Java.pptx
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling-160611180456 (1).pptx
unit 4 msbte syallbus for sem 4 2024-2025
Exceptionhandling
Exceptions in java
Exception handling in java
Java Exception Handling & IO-Unit-3 (1).ppt
Exception Handling,finally,catch,throw,throws,try.pptx
PACKAGES, INTERFACES AND EXCEPTION HANDLING
Java Day-5
L14 exception handling
Class notes(week 8) on exception handling
Z blue exception
Exception handling in java
Java-Unit 3- Chap2 exception handling
Chap2 exception handling
8.Exception handling latest(MB).ppt .
Ad

More from Parameshwar Maddela (11)

PPTX
EventHandling in object oriented programming
PPTX
working with interfaces in java programming
PPTX
introduction to object orinted programming through java
PPT
multhi threading concept in oops through java
PDF
Object oriented programming -QuestionBank
PPT
file handling in object oriented programming through java
PPTX
22H51A6755.pptx
PPTX
swings.pptx
PDF
03_Objects and Classes in java.pdf
PDF
02_Data Types in java.pdf
PPT
Intro tooop
EventHandling in object oriented programming
working with interfaces in java programming
introduction to object orinted programming through java
multhi threading concept in oops through java
Object oriented programming -QuestionBank
file handling in object oriented programming through java
22H51A6755.pptx
swings.pptx
03_Objects and Classes in java.pdf
02_Data Types in java.pdf
Intro tooop
Ad

Recently uploaded (20)

PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Introduction and Scope of Bichemistry.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Types of Literary Text: Poetry and Prose
PPTX
Onica Farming 24rsclub profitable farm business
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
NOI Hackathon - Summer Edition - GreenThumber.pptx
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
Insiders guide to clinical Medicine.pdf
Open Quiz Monsoon Mind Game Prelims.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
How to Manage Starshipit in Odoo 18 - Odoo Slides
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Introduction and Scope of Bichemistry.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
human mycosis Human fungal infections are called human mycosis..pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Types of Literary Text: Poetry and Prose
Onica Farming 24rsclub profitable farm business
Renaissance Architecture: A Journey from Faith to Humanism
The Final Stretch: How to Release a Game and Not Die in the Process.
Week 4 Term 3 Study Techniques revisited.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

Exception‐Handling in object oriented programming

  • 1. Exception Handling Fundamentals ‐ An exception is a problem that arises during the execution of a program. When an Exception(un wanted event) occurs the normal flow of the program is disrupted and the program/Application terminates abnormally. Some of the reasons for an exception • A user has entered an 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.
  • 2. If the exception Object is not Handled properly, the interpreter will display the error and will terminate the program. It is highly recommended to handle exceptions The main objective of exception handling is graceful termination of program. Exception handling doesn’t mean repairing an exception we have to provide alternative way to continue rest of the program normally is the concept of exception handling .
  • 3. exception handling can be managed by five keywords: 1.try, 2. catch, 3.throw, 4.throws, 5.finally.
  • 4. This is the general form of an exception-handling block try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } //…… finally { // block of code to be executed after try block ends }
  • 5. Uncaught Exceptions Class Test { public static void main(String args[]) { doStuff(); } public static doStuff() { doMoreStuff(); } public static doMoreStuff() { Java Runtime Stack System.out.println(10/0); } } doMoreStuff() doStuff() Main()
  • 6. Steps to handle Uncaught Exceptions 1.Inside a method if any exception occurs the method in which its raised is responsible to create exception object by including the following information 1.name of exception 2.description of exception 3.location at which exception occurs(stack trace) 2.After creation of exception object method handovers that object to the jvm. 3.Jvm will check whether the method contains any exception handling code or not if the method doesn’t contain exception handling code then jvm terminates that method abnormally and removes corresponding entry from the stack.
  • 7. 4. jvm identifies callers method and checks whether caller method contains any handling code or not. If the caller method doest contain handling code then jvm terminates that caller method also abnormally and removes corresponding entry from the stack this process will be continued until the main method. if the main method also doesn’t contain handling code then jvm terminates main method also abnormally and removes corresponding entry from the stack. 5.Then JVM handovers responsibility of exception handling to default exception handler, which is the part of jvm. 6.Defaulty Exception Handler prints exception information in the following format and terminates program abnormally. Exception in thread in XXX : name of the exception: Description: stack trace
  • 9. Exception Most of the times exceptions are caused by our program and these are recoverable. Child classes for Exception 1.IOException i.EOF Exception ii.FileNotFoundException iii.InteruptedIOException 2.SQLException 3.ServletExcetion 4.Runtime Exception i. ArithmeticException ii. NumberFormatException iii. ArrayIndexOutOfBoundsException iv.NullPointerException 5.RemoteException 6.Interuptedexception
  • 10. Error Most of the times errors are not caused by our program and these are due to lack of system resources. Errors are non recoverable. Child classes for Error 1.VMError i.StackOverFlowError ii.OutOfMemoryError 2.AssertionError
  • 11. Types of Exception There are mainly two types of exceptions 1.Checked Exception 2.Unchecked Exception Checked Exception: The exceptions which are checked by compiler for smooth execution of the program are called checked exception. Example: FileNotFoundException, SQLException In our program if there is chance of rising checked exception then compulsory we should handle that cheeked exception either by try, catch or throws key word otherwise we will get compile time error.
  • 12. Unchecked Exception The exception which are not checked by compiler whether programmer handling or not such type of exceptions are called Unchecked Exception. Example ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Note : 1.Whether it is checked or unchecked exception that occurs at runtime only there is no chance of occurring any exception at compile time. 2.RuntimeException and its child classes, Error and its child classes are unchecked except these reaming are checked.
  • 13. Exception Handling Using Try Catch It is highly recommended to handle exceptions. The code which may raise exception is called risky code and we have to define that code inside the try block. And the corresponding handling code we have to define inside the catch block. Syntax Try { Risky code } Catch(Exception e) { Handling code; }
  • 14. Example with out Try catch Class test { Public static void main(String args[]) { System.out.println(“statement1”); System.out.println(10/0); System.out.println(“statement3”); } } Out Put: Statement1 Exception:AE:divide by zero
  • 15. Example with Try catch Class test { Public static void main(String args[]) { System.out.println(“Before Exception ”); try { System.out.println(10/0); } Catch(ArithmeticException e) { System.out.println(10/2); } System.out.println(“After catch statement.”); } } Out Put: Statement1 5 Statement3
  • 16. Control Flow in Try Catch Try { Statement1 statement2 statement3 } Catch(Exception e) { statement4 } Statement5
  • 17. Case1: No Exception Out :1,2,3,5 -normal termination Case2: if an exception raised at statement 2 and corresponding catch block matched Out put:1,4,5-normal termination Case 3: if an exception raised at statement 2 and corresponding catch block not matched Out Put :1,-- abnormal termination Case 4: if an exception raised at statement 4 or statement 5 Out put: Abnormal termination Note : 1. With in the try block if any where exception raised then rest of the try block won’t be executed even though we handled exception. Hence we have to write only risky code into the try block. 2. In addition to try block there may be a chance of raising an exception inside catch and finally blocks. 3. If any statement which is not part of try block and raise an exception then it is always abnormal termination.
  • 18. Methods to print Exception Information Throwable class defines the following methods to print Exception Information Note : internally default exception handler will use printStackTrace to print exception information to the console Method Printable Format printStackTrace() Name of the Exception : Description : Stack Trace toString() Name of the Exception : Description getMessage() Description
  • 19. Example class Test { public static void main(String args[]) { try { system.out.println(10/0); } catch(ArithmeticException e) { e.printStackTrace(); System.out.println(e.toString()); System.out.println(e.getMessage()); } } } Java.lang:AE:/ by Zero At test.Main() Java.lang:AE: / by Zero / by Zero
  • 20. Try with multiple catch blocks The way of handling an exception is varied from exception to exception hence for every exception type, it is highly recommended to take separate catch block that is try with multiple catch blocks is always possible and recommended to use. Example Try { Risky code; } Catch(Exception e) { } Bad programming practice
  • 21. Example: Try { Risky code; } Catch(Arithmetic Exception e) { Perform any Arithmetic operation; } Catch(FileNotFoundException e) { Use local file instead of remote file; } Catch(Exception e) { //Default Exception Handling; } Best Programming Practice
  • 22. If try with multiple catch blocks present then the order of catch blocks is very important. We have to take child first and then parent otherwise we will get compile time error saying Exception XXX has already been caught Example Try { Risky code } Catch(Exception e) { } Catch(ArithmeticException e) { } Out put : Compile time error
  • 24. Nested try Statements One try-catch block can be present in the another try’s body. This is called Nesting of try catch blocks. Each time a try block does not have a catch handler for a particular exception, the stack is unwound and the next try block’s catch handlers are inspected for a match. If no catch block matches, then the java run-time system will handle the exception.
  • 25. Syntax of Nested try Catch .... //Main try block try { statement 1; statement 2; //try-catch block inside another try block try { statement 3; statement 4; } catch(Exception e1) { //Exception Message } } catch(Exception e3) //Catch of Main(parent) try block { //Exception Message }
  • 26. Throw Keyword Some times we can create exception object explicitly and handover to jvm manually, for this we have to use throw key word. Throw new ArithmeticException(“/ by zero”); The main objective of throw key word is to handover our created exception object to jvm manually. Example Class test { Public static void main(String args[]) { Throw new ArithmeticException(“/ by zero”); } } Best use of throw keyword is for user defined exceptions or customized exceptions.
  • 27. Throws keyword In our program if there is a possibility of raising checked exception then compulsory we should handle that checked exception otherwise we will get compile time error saying Unreported Exception XXX must be caught or declared to be thrown Syntax type method-name(parameter-list) throws exception-list { // body of method } Example Class test { Public static void main(String args[]) PrintWriter pw=new PrintWriter(“abc.txt”); pw.println(“hello”); } } Compile time error: Unreported Exception java.io.FileNotFound; must be caught or declared to be thrown
  • 28. We can handle this compile time error by using Throws keyword or by using Try catch. The purpose of throws keyword is to delegate the responsibility of exception handling to the caller (it may be another method or JVM) then caller method is responsible to handle that exception Example Class test { Public static void main(String args[]) throws FileNotFoundException { PrintWriter pw=new PrintWriter(“abc.txt”); pw.println(“hello”); } }
  • 29. Throws key word requires only for checked exception. Throws key word required only to convince compiler and usage of throws keyword doesn't prevent abnormal termination of the program.
  • 30. Finally block finally block is a block that is used to execute important(clean up) code such as closing connection, stream etc. finally block is always executed whether exception is handled or not. finally block follows try or catch block. Example Try { Risky code } Catch(Exception e) { } finally { Clean up code; }
  • 33. User defined Exception subclass We can also create our own exception sub class simply by extending java Exception class. Example class TooYoungException extends RuntimeException { TooYoungException(String s) { super(s); } } class CustException { public static void main(String args[]) { int age=Integer.parseInt(args[0]); if(age<18) { throw new TooYoungException("you are too young so u r not allowed"); } else { System.out.println("u r allowed"); } } }
  • 34. Chained Exception Chained Exception was added to Java in JDK 1.4. This feature allow you to relate one exception with another exception, i.e one exception describes cause of another exception. Two new constructors and two new methods were added to Throwable class to support chained exception. Throwable( Throwable cause ) Throwable( String str, Throwable cause ) getCause() and initCause() are the two methods added to Throwable class. getCause() method returns the actual cause associated with current exception. initCause() set an underlying cause(exception) with invoking exception.
  • 35. Example import java.io.IOException; public class ChainedException { public static void divide(int a, int b) { if(b==0) { ArithmeticException ae = new ArithmeticException("top layer"); ae.initCause( new IOException("cause") ); throw ae; } else { System.out.println(a/b); } } public static void main(String[] args) { Try { divide(5, 0); } catch(ArithmeticException ae) { System.out.println( "caught : " +ae); System.out.println("actual cause: "+ae.getCause()); } } }