SlideShare a Scribd company logo
Exception Handling
PRESENTED BY
S.KARTHIK
ASSISTANT PROFESSOR OF IT
PSG COLLEGE OF ARTS & SCIENCE
COIMBATORE - 14
Why??
 An Error is any unexpected result obtained from a program during execution.
 Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal
program termination.
 Errors should be handled by the programmer, to prevent them from reaching the user.
 When a program runs into a runtime error, the program terminates abnormally.
 How can you handle the runtime error so that the program can continue to run or terminate
gracefully?
Errors and Error Handling
 Some typical causes of errors:
 Memory errors (i.e. memory incorrectly allocated, memory leaks,
“null pointer”)
 File system errors (i.e. disk is full, disk has been removed)
 Network errors (i.e. network is down, URL does not exist)
 Calculation errors (i.e. divide by 0)
• Unexpected conditions
• Disrupt normal flow of program
• With exception handling, we can develop more robust programs
Exceptions
Exceptions
Exceptions are thrown
And can be caught.
How do you handle exceptions?
Exception handling is accomplished through
the “try – catch” mechanism, or by a “throws”
clause in the method declaration.
For any code that throws a checked
exception, you can decide to handle the
exception yourself, or pass the exception “up
the chain” (to a parent class).
Where do exceptions come from?
• JVM
OR
• Java Programs – can throw an exception
 What are they?
 An exception is a representation of an error condition or a situation that is not
the expected result of a method.
 Exceptions are built into the Java language and are available to all program
code.
 Exceptions isolate the code that deals with the error condition from regular
program logic.
Exception Types
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System Errors
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
Runtime Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-
bounds array, and numeric
errors.
Types of Exceptions
• Errors - serious and fatal problems
• Exceptions - can be thrown by any program, user can extend
• RuntimException - caused by illegal operations, thrown by JVM
(unchecked)
Checked Exceptions vs.
Unchecked Exceptions
RuntimeException, Error and their subclasses are known as unchecked
exceptions.
All other exceptions are known as checked exceptions - the compiler
forces the programmer to check and deal with the exceptions.
Checked or Unchecked Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Unchecked
exception.
Declaring, Throwing, and Catching
Exceptions
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
catch exception throwexception
declare exception
Checked Exceptions
Checked exceptions that can be thrown in a method must be
• caught and handled
OR
• declared in the throws clause
Declaring Exceptions
Every method must state the types of checked exceptions it might
throw. This is known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
Throwing Exceptions
When the program detects an error, the program can create an
instance of an appropriate exception type and throw it. This is known
as throwing an exception. Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Catching Exceptions
try
catch
try
catch
try
catch
An exception
is thrown in
method3
Call Stack
main method main method
method1
main method
method1
main method
method1
method2 method2
method3
Catch or Declare Checked Exceptions
If a method declares a checked exception, you must invoke it in a try-catch block or declare
to throw the exception in the calling method.
In this example, method p1 invokes method p2 and p2 may throw a checked exception
(e.g., IOException)
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a) (b)
void p1() throws IOException {
p2();
}
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose no
exceptions in the
statements
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is
always executed
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next Statement;
Next statement;
Next statement in the
method is executed
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
statement2 throws an
exception of type
Exception2.
Trace a Program Execution
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Handling exception
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Execute the final block
Cautions When Using Exceptions
• Exception handling separates error-handling code from normal
programming tasks, thus making programs easier to read and to
modify.
• Exception handling usually requires more time and resources because
it requires instantiating a new exception object, rolling back the call
stack, and propagating the errors to the calling methods.
When to Throw Exceptions
• An exception occurs in a method.
• If you want the exception to be processed by its caller, you should
create an exception object and throw it.
• If you can handle the exception in the method where it occurs, there
is no need to throw it.
When to Use Exceptions
When should you use the try-catch block in the code? You should use it
to deal with unexpected error conditions. Do not use it to deal with
simple, expected situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
Creating Custom Exception Classes
 Use the exception classes in the API whenever possible.
 Create custom exception classes if the predefined classes are not sufficient.
 Declare custom exception classes by extending Exception or a subclass of
Exception.
Exceptions and Inheritance
How do you think exceptions affect overridden methods?
• if a method overrides a base class method, the new method cannot
throw a more general error, but can throw more specific.
• if the base class method throws no errors, the subclass method can't
either.
Thank You

More Related Content

PPTX
Exception handling
PPSX
How to handle exceptions in Java Technology
PPTX
Exception handling in Java
PPTX
Java exception handling
PPT
Java: Exception
PPT
Java exception
PPT
Exception handling in java
PPT
Exception Handling Java
Exception handling
How to handle exceptions in Java Technology
Exception handling in Java
Java exception handling
Java: Exception
Java exception
Exception handling in java
Exception Handling Java

What's hot (20)

PPT
Exception handling
PPT
Exception handling
PDF
Exception handling
PPTX
Exception handling in java
PPT
12 exception handling
PPT
Exception handling
PPTX
Exception handling
PPT
Exception handling
PDF
Best Practices in Exception Handling
ODP
Exception Handling In Java
PPT
Exception handling
PPTX
Exception Handling
PPTX
Exception handling in ASP .NET
PPTX
Exception handling in asp.net
PPT
Exception handling and templates
PPTX
Exception Handling in Java
PPTX
Exceptions in Java
PPTX
Exception handling in java
PPTX
Exception Handling in C++
PPTX
Z blue exception
Exception handling
Exception handling
Exception handling
Exception handling in java
12 exception handling
Exception handling
Exception handling
Exception handling
Best Practices in Exception Handling
Exception Handling In Java
Exception handling
Exception Handling
Exception handling in ASP .NET
Exception handling in asp.net
Exception handling and templates
Exception Handling in Java
Exceptions in Java
Exception handling in java
Exception Handling in C++
Z blue exception
Ad

Similar to Exception handling (20)

PPTX
JAVA Presenttation topics Programs.pptx
PPTX
Exception handling in Java
PDF
Class notes(week 8) on exception handling
PPTX
Exceptions overview
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPT
JP ASSIGNMENT SERIES PPT.ppt
DOCX
Class notes(week 8) on exception handling
PPTX
Java -Exception handlingunit-iv
PPT
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
PPT
Itp 120 Chapt 18 2009 Exceptions & Assertions
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PDF
Java exception handling ppt
PPTX
Interface andexceptions
PPTX
java exception.pptx
PPTX
Exception‐Handling in object oriented programming
PPT
Exception Handling in java masters of computer application
PPTX
Exception handling in java
PDF
Introduction to Exception
PPTX
UNIT 2.pptx
JAVA Presenttation topics Programs.pptx
Exception handling in Java
Class notes(week 8) on exception handling
Exceptions overview
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
JP ASSIGNMENT SERIES PPT.ppt
Class notes(week 8) on exception handling
Java -Exception handlingunit-iv
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Itp 120 Chapt 18 2009 Exceptions & Assertions
unit 4 msbte syallbus for sem 4 2024-2025
Java exception handling ppt
Interface andexceptions
java exception.pptx
Exception‐Handling in object oriented programming
Exception Handling in java masters of computer application
Exception handling in java
Introduction to Exception
UNIT 2.pptx
Ad

Recently uploaded (20)

PDF
Computing-Curriculum for Schools in Ghana
PDF
Complications of Minimal Access Surgery at WLH
PPTX
master seminar digital applications in india
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 Đ...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharma ospi slides which help in ospi learning
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Pre independence Education in Inndia.pdf
PPTX
Institutional Correction lecture only . . .
PDF
Sports Quiz easy sports quiz sports quiz
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
Computing-Curriculum for Schools in Ghana
Complications of Minimal Access Surgery at WLH
master seminar digital applications in india
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Anesthesia in Laparoscopic Surgery in India
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharma ospi slides which help in ospi learning
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Microbial disease of the cardiovascular and lymphatic systems
01-Introduction-to-Information-Management.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Pre independence Education in Inndia.pdf
Institutional Correction lecture only . . .
Sports Quiz easy sports quiz sports quiz
TR - Agricultural Crops Production NC III.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?

Exception handling

  • 1. Exception Handling PRESENTED BY S.KARTHIK ASSISTANT PROFESSOR OF IT PSG COLLEGE OF ARTS & SCIENCE COIMBATORE - 14
  • 2. Why??  An Error is any unexpected result obtained from a program during execution.  Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination.  Errors should be handled by the programmer, to prevent them from reaching the user.  When a program runs into a runtime error, the program terminates abnormally.  How can you handle the runtime error so that the program can continue to run or terminate gracefully?
  • 3. Errors and Error Handling  Some typical causes of errors:  Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”)  File system errors (i.e. disk is full, disk has been removed)  Network errors (i.e. network is down, URL does not exist)  Calculation errors (i.e. divide by 0)
  • 4. • Unexpected conditions • Disrupt normal flow of program • With exception handling, we can develop more robust programs Exceptions
  • 5. Exceptions Exceptions are thrown And can be caught. How do you handle exceptions? Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
  • 6. Where do exceptions come from? • JVM OR • Java Programs – can throw an exception  What are they?  An exception is a representation of an error condition or a situation that is not the expected result of a method.  Exceptions are built into the Java language and are available to all program code.  Exceptions isolate the code that deals with the error condition from regular program logic.
  • 8. System Errors LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
  • 9. Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • 10. Runtime Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException RuntimeException is caused by programming errors, such as bad casting, accessing an out-of- bounds array, and numeric errors.
  • 11. Types of Exceptions • Errors - serious and fatal problems • Exceptions - can be thrown by any program, user can extend • RuntimException - caused by illegal operations, thrown by JVM (unchecked)
  • 12. Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions - the compiler forces the programmer to check and deal with the exceptions.
  • 13. Checked or Unchecked Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Unchecked exception.
  • 14. Declaring, Throwing, and Catching Exceptions method1() { try { invoke method2; } catch (Exception ex) { Process exception; } } method2() throws Exception { if (an error occurs) { throw new Exception(); } } catch exception throwexception declare exception
  • 15. Checked Exceptions Checked exceptions that can be thrown in a method must be • caught and handled OR • declared in the throws clause
  • 16. Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException
  • 17. Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex;
  • 18. Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
  • 19. Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }
  • 20. Catching Exceptions try catch try catch try catch An exception is thrown in method3 Call Stack main method main method method1 main method method1 main method method1 method2 method2 method3
  • 21. Catch or Declare Checked Exceptions If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method. In this example, method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException) void p1() { try { p2(); } catch (IOException ex) { ... } } (a) (b) void p1() throws IOException { p2(); }
  • 22. The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }
  • 23. Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
  • 24. Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
  • 25. Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next Statement; Next statement; Next statement in the method is executed
  • 26. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } statement2 throws an exception of type Exception2. Trace a Program Execution
  • 27. Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Handling exception
  • 28. Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Execute the final block
  • 29. Cautions When Using Exceptions • Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. • Exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
  • 30. When to Throw Exceptions • An exception occurs in a method. • If you want the exception to be processed by its caller, you should create an exception object and throw it. • If you can handle the exception in the method where it occurs, there is no need to throw it.
  • 31. When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }
  • 32. When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");
  • 33. Creating Custom Exception Classes  Use the exception classes in the API whenever possible.  Create custom exception classes if the predefined classes are not sufficient.  Declare custom exception classes by extending Exception or a subclass of Exception.
  • 34. Exceptions and Inheritance How do you think exceptions affect overridden methods? • if a method overrides a base class method, the new method cannot throw a more general error, but can throw more specific. • if the base class method throws no errors, the subclass method can't either.