SlideShare a Scribd company logo
What is an exception?
 An exception or exceptional event is an event that occurs
during the execution of a program that disrupts the
normal flow of instructions
 The following will cause exceptions:
 Accessing an out-of-bounds array element
 Writing into a read-only file
 Trying to read beyond the end of a file
 Sending illegal arguments to a method
 Performing illegal arithmetic (e.g divide by 0)
 Hardware failures
Why Use Exceptions?
 Compilation cannot find all errors
 To separate error handling code from regular code
 Code clarity (debugging, teamwork, etc.)
 Worry about handling error elsewhere
 To separate error detection, reporting, and handling
 To group and differentiate error types
 Write error handlers that handle very specific exceptions
In java
 In java exceptions are objects.
 When you throw an exception, you throw an object.
 You can't throw just any object as an exception, -- only
those objects whose classes descend from Throwable.
 Throwable serves as the base class for an entire family of
classes, declared in java.lang, that your program can
instantiate and throw.
In java
 A small part of this family is shown in Figure below
Exception Terminology In java
 Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.
 try: Program statements that you want to monitor for
exceptions are contained within a try block
 catch: If an exception occurs within the try block, it is
thrown. Your code can catch this exception (using catch)
and handle it in some rational manner.
(System-generated exceptions are automatically thrown by
the Java run-time system.)
Exception Terminology In java
 throw: To manually throw an exception, use the keyword
throw.
 throws: Any exception that is thrown out of a method
must be specified as such by a throws clause
 finally: Any code that absolutely must be executed after
a try block completes is put in a finally block.
Exception Terminology
 When an exception occurs, we say it was thrown or raised
 When an exception is dealt with, we say it is handled or
caught
 The block of code that deals with exceptions is known as
an exception handler
In java
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 In java
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Uncaught Exceptions In java
 When the Java run-time system detects the attempt to
divide by zero, it constructs a new exception object and
then throws this exception.
 once an exception has been thrown, it must be caught by
an exception handler and dealt with immediately.
 In this example, we haven’t supplied any exception
handlers of our own, so the exception is caught by the
default handler provided by the Java run-time system.
Uncaught Exceptions In java
 The default handler displays a string describing the
exception, prints a stack trace from the point at which the
exception occurred, and terminates the program.
 Here is the exception generated when this example is
executed:
java.lang.ArithmeticException: / by zero at
Exc0.main(Exc0.java:4)
Decoding Exception Messages
public class ArrayExceptionExample {
public static void main(String args[]) {
String[] names = {“Bilal", “Robert"};
System.out.println(names[2]);
}
}
 The println in the above code causes an exception
to be thrown with the following exception message:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2 at
ArrayExceptionExample.main(ArrayExceptionExamp le.java:4)
Exception Message Format
Exception messages have
the following format:
[exception class]: [additional description
of exception] at
[class].[method]([file]:[line number]
Exception Messages Example
 Exception message from array example
java.lang.ArrayIndexOutOfBoundsException: 2 at
ArrayExceptionExample.main(ArrayExceptionExample.java:4
)
 What is the exception class?
java.lang.ArrayIndexOutOfBoundsException
 Which array index is out of bounds?
2
 What method throws the exception?
ArrayExceptionExample.main
 What file contains the method?
ArrayExceptionExample.java
 What line of the file throws the exception?
stack trace
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
stack trace
 The resulting stack trace from the default exception
handler shows how the entire call
stack is displayed:
 java.lang.ArithmeticException: / by zero
 at Exc1.subroutine(Exc1.java:4)
 at Exc1.main(Exc1.java:7)
Using try and catch
 Although the default exception handler provided by the
Java run-time system is useful for debugging, you will
usually want to handle an exception yourself.
 Doing so provides two benefits.
 First, it allows you to fix the error.
 Second, it prevents the program from automatically
terminating.
Using try and catch
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Using try and catch
// Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}System.out.println("a: " + a);
}}}
Handling Exceptions
 Can use a try-catch block to handle exceptions that are thrown
try{
// code that might throw exception
}
catch([Type of Exception] e) {
// what to do if exception is thrown
}
Handling Multiple Exceptions
 Can handle multiple possible exceptions by multiple successive catch blocks
 try{
 // code that might throw multiple
 // exceptions
 }
 catch (IOException e) {
 // handle IOException
 }
 catch (ClassNotFoundException e2) {
 // handle ClassNotFoundException
 }
Nested try
 Try statement can be inside the block of another try.
 Each time a try statement is entered, the context of that
exception is pushed on the stack.
 If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
 This continues until one of the catch statements succeeds, or
until all of the nested try statements are exhausted.
 If no catch statement matches, then the Java run-time
system will handle the exception.
throw
 It is possible for your program to throw an exception
explicitly, using the throw statement.
 The general form of throw is shown here:
 Throw ThrowableInstance;
throw
 There are two ways you can obtain a Throwable object:
 using a parameter in a catch clause, or
 creating one with the new operator.
 The flow of execution stops immediately after the throw
statement;
 any subsequent statements are not executed.
 The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of exception.
throw
 If it does find a match, control is transferred to that
statement.
 If not, then the next enclosing try statement is inspected,
and so on.
 If no matching catch is found, then the default exception
handler halts the program and prints the stack trace.
throws
 If a method is capable of causing an exception that it
does not handle, it must specify this behavior so that
callers of the method can guard themselves against that
exception.
 You do this by including a throws clause in the method’s
declaration
throws
 This is the general form of a method declaration that
includes a throws clause:
 type method-name(parameter-list) throws exception-list
{
// body of method
}
Finally Block
 Can also use the optional finally block at the end of the
try-catch block
 finally block provides a mechanism to clean up regardless
of what happens within the try block
 Can be used to close files or to release other system
resources
Try-Catch-Finally Block
try{
// code that might throw exception
}
catch([Type of Exception] e) {
// what to do if exception is thrown
}
finally{
// statements here always get
// executed, regardless of what
// happens in the try block}
Unchecked Exceptions
 Unchecked exceptions or RuntimeExceptions occur within
the Java runtime system
 Examples of unchecked exceptions
 arithmetic exceptions (dividing by zero)
 pointer exceptions (trying to access an object’s members
through a null reference)
 indexing exceptions (trying to access an array element with
an index that is too large or too small)
 A method does not have to catch or specify that it throws
unchecked exceptions, although it may.
More on Unchecked Exceptions
 Can occur at many points in the program
 Program handling such exceptions would be cluttered,
pointlessly
 Only handle unchecked exceptions at important program
points
Checked Exceptions
 Those other exceptions that the compiler can detect
easily.
 Usually originate in library code
 For example, exceptions occurring during I/O, Files
 Compiler ensures that: checked exceptions are:
 caught using try-catch or
 are specified to be passed up to calling method
Handling Checked Exceptions
 Every method must catch checked exceptions OR specify that it passes them to the caller (using the throws
keyword)
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
catch (FileNotFoundException e) {
System.out.println("file was not found");
}
} OR
void readFile(String filename)throws FileNotFoundException
{
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
Writing Your Own Exceptions
 At least 2 types of exception
constructors exist:
1. Default constructor: No arguments
NullPointerException e = new
NullPointerException();
2. Constructor that has a detailed message: Has a single String
argument
IllegalArgumentExceptione e =
new IllegalArgumentException(“Number
must be positive");
Writing Your Own Exceptions
 Your own exceptions must be a subclass of the Exception class and have
at least the two standard constructors
public class MyCheckedException extends IOException {
public MyCheckedException() {}
public MyCheckedException(String m){
super(m);}
}
public class MyUncheckedException extends
RuntimeException {
public MyUncheckedException() {}
public MyUncheckedException(String m) {super(m);}
}
Checked or Unchecked?
 If a user can reasonably be expected to recover from an
exception, make it a checked exception
 If a user cannot do anything to recover from the
exception, make it an unchecked exception
 Judgment call on the part of the designers of the Java
programming language
 http://java.sun.com/docs/books/jls/second_edition/html/
exceptions.doc.html
Exception Class hierarchy
Lecture Summary
 Exceptions disrupt the normal flow of the instructions in
the program
 Exceptions are handled using a try-catch or a try-catch-
finally block
 A method throws an exception using the throw statement
 A method does not have to catch or specify that it throws
unchecked exceptions, although it may.
Lecture Summary
 Every method must catch possible checked exceptions or
specify that it may throw them
 If you write your own exception, it must be a subclass of
the Exception class
 Define the two standard constructors

More Related Content

What's hot (20)

PPTX
Java exception handling
BHUVIJAYAVELU
 
PPTX
Java - Exception Handling
Prabhdeep Singh
 
PPT
Java exception
Arati Gadgil
 
PPTX
Exception handling in java
yugandhar vadlamudi
 
PPTX
130410107010 exception handling
Hemant Chetwani
 
PPT
exception handling
Manav Dharman
 
ODP
Exception handling in java
priyankazope
 
PPTX
Exception handling in Java
Prasad Sawant
 
PPTX
Exception handling in java
pooja kumari
 
PPT
Exception handling
Raja Sekhar
 
PPTX
Exception handling
Ardhendu Nandi
 
PDF
Java - Exception Handling Concepts
Victer Paul
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPT
Java: Exception
Tareq Hasan
 
DOCX
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 
PPTX
Exceptionhandling
Nuha Noor
 
PPT
Types of exceptions
myrajendra
 
PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PPT
Multi catch statement
myrajendra
 
Java exception handling
BHUVIJAYAVELU
 
Java - Exception Handling
Prabhdeep Singh
 
Java exception
Arati Gadgil
 
Exception handling in java
yugandhar vadlamudi
 
130410107010 exception handling
Hemant Chetwani
 
exception handling
Manav Dharman
 
Exception handling in java
priyankazope
 
Exception handling in Java
Prasad Sawant
 
Exception handling in java
pooja kumari
 
Exception handling
Raja Sekhar
 
Exception handling
Ardhendu Nandi
 
Java - Exception Handling Concepts
Victer Paul
 
Exception Handling in JAVA
SURIT DATTA
 
Java: Exception
Tareq Hasan
 
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 
Exceptionhandling
Nuha Noor
 
Types of exceptions
myrajendra
 
Exception Handling in Java
lalithambiga kamaraj
 
Multi catch statement
myrajendra
 

Similar to Interface andexceptions (20)

PPTX
Java-Unit 3- Chap2 exception handling
raksharao
 
PPTX
Exception Handling.pptx
primevideos176
 
PPTX
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
DOCX
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
PPTX
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
PPT
8.Exception handling latest(MB).ppt .
happycocoman
 
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
 
PPT
Exception Handling in java masters of computer application
xidileh999
 
PPTX
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
PPTX
java exception.pptx
SukhpreetSingh519414
 
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Java-Unit 3- Chap2 exception handling
raksharao
 
Exception Handling.pptx
primevideos176
 
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
8.Exception handling latest(MB).ppt .
happycocoman
 
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
 
Exception Handling in java masters of computer application
xidileh999
 
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
java exception.pptx
SukhpreetSingh519414
 
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Ad

More from saman Iftikhar (14)

PDF
This-that-these-those.pdf
saman Iftikhar
 
PDF
project planning components.pdf
saman Iftikhar
 
PDF
02Data updated.pdf
saman Iftikhar
 
PDF
Clustering.pdf
saman Iftikhar
 
PDF
networking lab
saman Iftikhar
 
PPTX
Science
saman Iftikhar
 
PPTX
O p
saman Iftikhar
 
PPTX
Ethical principles in psychological research
saman Iftikhar
 
PPTX
polysemy tag detect in tag sets
saman Iftikhar
 
PPTX
Selection
saman Iftikhar
 
DOCX
Pipeline
saman Iftikhar
 
PPTX
Context diagram
saman Iftikhar
 
DOCX
Database
saman Iftikhar
 
PPTX
Flags registers
saman Iftikhar
 
This-that-these-those.pdf
saman Iftikhar
 
project planning components.pdf
saman Iftikhar
 
02Data updated.pdf
saman Iftikhar
 
Clustering.pdf
saman Iftikhar
 
networking lab
saman Iftikhar
 
Science
saman Iftikhar
 
Ethical principles in psychological research
saman Iftikhar
 
polysemy tag detect in tag sets
saman Iftikhar
 
Selection
saman Iftikhar
 
Pipeline
saman Iftikhar
 
Context diagram
saman Iftikhar
 
Database
saman Iftikhar
 
Flags registers
saman Iftikhar
 
Ad

Recently uploaded (20)

PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 

Interface andexceptions

  • 1. What is an exception?  An exception or exceptional event is an event that occurs during the execution of a program that disrupts the normal flow of instructions  The following will cause exceptions:  Accessing an out-of-bounds array element  Writing into a read-only file  Trying to read beyond the end of a file  Sending illegal arguments to a method  Performing illegal arithmetic (e.g divide by 0)  Hardware failures
  • 2. Why Use Exceptions?  Compilation cannot find all errors  To separate error handling code from regular code  Code clarity (debugging, teamwork, etc.)  Worry about handling error elsewhere  To separate error detection, reporting, and handling  To group and differentiate error types  Write error handlers that handle very specific exceptions
  • 3. In java  In java exceptions are objects.  When you throw an exception, you throw an object.  You can't throw just any object as an exception, -- only those objects whose classes descend from Throwable.  Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw.
  • 4. In java  A small part of this family is shown in Figure below
  • 5. Exception Terminology In java  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  try: Program statements that you want to monitor for exceptions are contained within a try block  catch: If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner. (System-generated exceptions are automatically thrown by the Java run-time system.)
  • 6. Exception Terminology In java  throw: To manually throw an exception, use the keyword throw.  throws: Any exception that is thrown out of a method must be specified as such by a throws clause  finally: Any code that absolutely must be executed after a try block completes is put in a finally block.
  • 7. Exception Terminology  When an exception occurs, we say it was thrown or raised  When an exception is dealt with, we say it is handled or caught  The block of code that deals with exceptions is known as an exception handler
  • 8. In java 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 }
  • 9. Uncaught Exceptions In java class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } }
  • 10. Uncaught Exceptions In java  When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception.  once an exception has been thrown, it must be caught by an exception handler and dealt with immediately.  In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system.
  • 11. Uncaught Exceptions In java  The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.  Here is the exception generated when this example is executed: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
  • 12. Decoding Exception Messages public class ArrayExceptionExample { public static void main(String args[]) { String[] names = {“Bilal", “Robert"}; System.out.println(names[2]); } }  The println in the above code causes an exception to be thrown with the following exception message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ArrayExceptionExample.main(ArrayExceptionExamp le.java:4)
  • 13. Exception Message Format Exception messages have the following format: [exception class]: [additional description of exception] at [class].[method]([file]:[line number]
  • 14. Exception Messages Example  Exception message from array example java.lang.ArrayIndexOutOfBoundsException: 2 at ArrayExceptionExample.main(ArrayExceptionExample.java:4 )  What is the exception class? java.lang.ArrayIndexOutOfBoundsException  Which array index is out of bounds? 2  What method throws the exception? ArrayExceptionExample.main  What file contains the method? ArrayExceptionExample.java  What line of the file throws the exception?
  • 15. stack trace class Exc1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); } }
  • 16. stack trace  The resulting stack trace from the default exception handler shows how the entire call stack is displayed:  java.lang.ArithmeticException: / by zero  at Exc1.subroutine(Exc1.java:4)  at Exc1.main(Exc1.java:7)
  • 17. Using try and catch  Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself.  Doing so provides two benefits.  First, it allows you to fix the error.  Second, it prevents the program from automatically terminating.
  • 18. Using try and catch class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } }
  • 19. Using try and catch // Handle an exception and move on. import java.util.Random; class HandleError { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<32000; i++) { try { b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c); } catch (ArithmeticException e) { System.out.println("Division by zero."); a = 0; // set a to zero and continue }System.out.println("a: " + a); }}}
  • 20. Handling Exceptions  Can use a try-catch block to handle exceptions that are thrown try{ // code that might throw exception } catch([Type of Exception] e) { // what to do if exception is thrown }
  • 21. Handling Multiple Exceptions  Can handle multiple possible exceptions by multiple successive catch blocks  try{  // code that might throw multiple  // exceptions  }  catch (IOException e) {  // handle IOException  }  catch (ClassNotFoundException e2) {  // handle ClassNotFoundException  }
  • 22. Nested try  Try statement can be inside the block of another try.  Each time a try statement is entered, the context of that exception is pushed on the stack.  If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match.  This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted.  If no catch statement matches, then the Java run-time system will handle the exception.
  • 23. throw  It is possible for your program to throw an exception explicitly, using the throw statement.  The general form of throw is shown here:  Throw ThrowableInstance;
  • 24. throw  There are two ways you can obtain a Throwable object:  using a parameter in a catch clause, or  creating one with the new operator.  The flow of execution stops immediately after the throw statement;  any subsequent statements are not executed.  The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception.
  • 25. throw  If it does find a match, control is transferred to that statement.  If not, then the next enclosing try statement is inspected, and so on.  If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
  • 26. throws  If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.  You do this by including a throws clause in the method’s declaration
  • 27. throws  This is the general form of a method declaration that includes a throws clause:  type method-name(parameter-list) throws exception-list { // body of method }
  • 28. Finally Block  Can also use the optional finally block at the end of the try-catch block  finally block provides a mechanism to clean up regardless of what happens within the try block  Can be used to close files or to release other system resources
  • 29. Try-Catch-Finally Block try{ // code that might throw exception } catch([Type of Exception] e) { // what to do if exception is thrown } finally{ // statements here always get // executed, regardless of what // happens in the try block}
  • 30. Unchecked Exceptions  Unchecked exceptions or RuntimeExceptions occur within the Java runtime system  Examples of unchecked exceptions  arithmetic exceptions (dividing by zero)  pointer exceptions (trying to access an object’s members through a null reference)  indexing exceptions (trying to access an array element with an index that is too large or too small)  A method does not have to catch or specify that it throws unchecked exceptions, although it may.
  • 31. More on Unchecked Exceptions  Can occur at many points in the program  Program handling such exceptions would be cluttered, pointlessly  Only handle unchecked exceptions at important program points
  • 32. Checked Exceptions  Those other exceptions that the compiler can detect easily.  Usually originate in library code  For example, exceptions occurring during I/O, Files  Compiler ensures that: checked exceptions are:  caught using try-catch or  are specified to be passed up to calling method
  • 33. Handling Checked Exceptions  Every method must catch checked exceptions OR specify that it passes them to the caller (using the throws keyword) void readFile(String filename) { try { FileReader reader = new FileReader("myfile.txt"); // read from file . . . } catch (FileNotFoundException e) { System.out.println("file was not found"); } } OR void readFile(String filename)throws FileNotFoundException { FileReader reader = new FileReader("myfile.txt"); // read from file . . . }
  • 34. Writing Your Own Exceptions  At least 2 types of exception constructors exist: 1. Default constructor: No arguments NullPointerException e = new NullPointerException(); 2. Constructor that has a detailed message: Has a single String argument IllegalArgumentExceptione e = new IllegalArgumentException(“Number must be positive");
  • 35. Writing Your Own Exceptions  Your own exceptions must be a subclass of the Exception class and have at least the two standard constructors public class MyCheckedException extends IOException { public MyCheckedException() {} public MyCheckedException(String m){ super(m);} } public class MyUncheckedException extends RuntimeException { public MyUncheckedException() {} public MyUncheckedException(String m) {super(m);} }
  • 36. Checked or Unchecked?  If a user can reasonably be expected to recover from an exception, make it a checked exception  If a user cannot do anything to recover from the exception, make it an unchecked exception  Judgment call on the part of the designers of the Java programming language  http://java.sun.com/docs/books/jls/second_edition/html/ exceptions.doc.html
  • 38. Lecture Summary  Exceptions disrupt the normal flow of the instructions in the program  Exceptions are handled using a try-catch or a try-catch- finally block  A method throws an exception using the throw statement  A method does not have to catch or specify that it throws unchecked exceptions, although it may.
  • 39. Lecture Summary  Every method must catch possible checked exceptions or specify that it may throw them  If you write your own exception, it must be a subclass of the Exception class  Define the two standard constructors