Java Exception Handling
Outline
What exceptions are for
What exceptions are NOT for
Catching & Throwing exceptions
Exception Specifications
Standard Java Exceptions
The finally clause
Uncaught Exceptions
What Exceptions are For
To handle Bad Things
 I/O errors, other runtime errors
 when a function fails to fulfill its specification
 so you can restore program stability (or exit
gracefully)
What Exceptions are For
~ continued ~
To force you to handle Bad Things
 because return codes can be tedious
 and sometimes you’re lazy
To signal errors from constructors
 because constructors have no return value
Example
File I/O
public FileReader(String fileName)
throws FileNotFoundException
public void close() throws IOException
import java.io.*;
class OpenFile
{
public static void main(String[] args)
{
if (args.length > 0)
{
try
{
// Open a file:
FileReader f =
new FileReader(args[0]);
System.out.println(args[0]
+ " opened");
f.close();
}
catch (IOException x)
{
System.out.println(x);
}
}
}
}
What Exceptions are NOT For
NOT For Alternate Returns:
 e.g., when end-of-file is reached:
while ((s = f.readLine()) != null) …
Exceptions are only for the exceptional!
Catching Exceptions
Wrap code to be checked in a try-block
 checking occurs all the way down the execution
stack
try-blocks can be nested
 control resumes at most enclosed matching
handler
Working of try-catch
try block
Statement that causes
an exception
Catch block
Statement that
handles the
exception
Throws exception
object
Exception object creator
Exception handler
Catching Exceptions
~ continued ~
Place one or more catch-clauses after try-
block
 runtime system looks back up the call stack for
a matching handler
 subclass types match superclass types
 catching Exception catches everything (almost)
 handlers are checked in the order they appear
 place most derived types first!
 execution resumes after last handler
 if you let it (could branch or throw)
Multiple catch statements
syntax:
Try
{
Statement; //generates an exception
}
Catch(Exception type1 e)
{Statement;}
Catch(Exception type2 e1)
{Statement;}
……..
…….
Throwing Exceptions
Must throw objects derived (ultimately) from
Throwable
Usually derive from java.lang.Exception
The class name is the most important attribute of
an exception
Can optionally include a message
 Provide two constructors:
 MyException( )
 MyException(String s)
Throwing Exceptions
~ continued ~
Control is passed up the execution stack to
a matching handler
Various methods exist for processing
exceptions:
 getMessage( )
 toString( ) (class name + message)
 printStackTrace( )
Throwing Exceptions
~ continued ~
Functions must “advertise” their exceptions
 every function must specify the “checked”
exceptions it (or its callees!) may throw
Callers must do one of two things:
 handle your exceptions with try-catch, or
 advertise your exceptions along with theirs
Standard Java Exceptions
Throwable
Exception Error
RuntimeException IOException . . .
Class java.lang.Exception
The one you usually derive from
“Checked Exceptions”
 specifications checked at compile time
 you must either catch or advertise these
 Used for recoverable errors
 Not programmer errors
java.lang.Exception Subclasses
~ sample ~
AWTException
ClassNotFoundException
CloneNotSupportedException
IOException
NoSuchFieldException
Class java.lang.Error
For JVM Failures and other Weird Things
 let program terminate
InternalError is one of these
Don’t catch them
 you don’t know what to do!
These are “unchecked exceptions”
 not required to advertise
java.lang.Error Subclasses
AWTError
LinkageError
 …
ThreadDeath
VirtualMachineError
 InternalError, OutOfMemoryError,
StackOverflowError, UnknownError
Class java.lang.RuntimeException
Stupid Name!
 Same as logic_error in C++
Program logic errors
 e.g., bad cast, using a null handle, array index
violation, etc.
 Shouldn’t happen!
 fixed during testing
 Similar in spirit to C’s assert( ) macro
 mainly for debugging
These are called “unchecked exceptions”
java.lang.RuntimeException
Subclasses (sample)
ArithmeticException (e.g., divide by 0)
ArrayStoreException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NullPointerException
UnsupportedOperationException
The finally Clause
For code that must ALWAYS run
 No matter what!
 Even if a return or break occurs first
 Exception: System.exit( )
Placed after handlers (if they exist)
 try-block must either have a handler or a
finally-block
The finally Clause
~ continued ~
 The finally can be used to handle an exception (ie) not caught by any of the
previous catch statement.
 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.
Syntax:
try{ try{
…..} …..}
finally{ catch(…){
……} …..}
finally{
……}
Exception-handling Syntax
~ The Whole Picture ~
try
{
// normal code (conditionally executes)
}
catch (ExceptionType1 x)
{
// handle ExceptionType1 error
}
…
catch (ExceptionTypeN x)
{
// handle ExceptionTypeN error
}
finally
{
// invariant code ("always" executes)
}
class FinallyTest
{
public static void f()
throws Exception
{
try
{
// 0
// return; // 1
// System.exit(0); // 2
// throw new Exception(); // 3a
}
catch (Exception x)
{
// throw new Exception(); // 3b
}
finally
{
System.out.println("finally!");
}
System.out.println("last statement");
}
public static void main(String[] args)
{
try
{
f();
}
catch(Exception x)
{}
}
}
Program Output
0:
finally!
last statement
1:
finally!
2:
(no output)
3a:
same as 0:
3a + 3b:
compiler error (last statement not reachable)
When to Handle Exceptions
Note: Manage.f( ) didn’t catch anything
 wouldn’t know what to do if it did!
You often let exceptions pass up the call
stack
Or you can re-throw in a catch
 throw x; // in a handler where x was caught
 or re-throw a new type of exception
Exception Etiquette
Don’t catch what you can’t (at least
partially) handle
 re-throw if only partially handled (“catch &
release”: if you’re not going to eat it, throw it
back!)
Don’t catch & ignore
 catch (Exception x){} // disables exceptions!
How Exceptions Work
When an exception is thrown execution
backtracks up the runtime stack (list of active
function invocations)
Each stack frame contains information regarding
local handlers, if any
 Otherwise, execution returns up to the next caller,
looking for a suitable catch
What happens if there isn’t a matching catch?
Uncaught Exceptions
What if there is no handler for an
exception?
The thread dies!
 exceptions belong to a thread (stack-specific)
Throwing our own Exceptions
Syntax:
Throw new throwable_subclass;
Ex:
Throw new Arithmetic Exception();
Program
import java.lang.Exception;
class my extends Exception {
my(String msg);}
class test
{ public static void main(String a[])
{ int x=5,y=1000;
try {float z=(float) x / (float) y;
if(z<0.01)
{ throw new my(“Number is to small”); }
}
Catch(my e)
{ S.o.p(“Caught my exception”);
S.o.p(“e.getMessage()); }
~ continued ~
Finally
{ S.o.p(“I am always here”);
} } }
O/P:
Caught my exception
Number is to small
I am always here

Exception handling

  • 1.
  • 2.
    Outline What exceptions arefor What exceptions are NOT for Catching & Throwing exceptions Exception Specifications Standard Java Exceptions The finally clause Uncaught Exceptions
  • 3.
    What Exceptions areFor To handle Bad Things  I/O errors, other runtime errors  when a function fails to fulfill its specification  so you can restore program stability (or exit gracefully)
  • 4.
    What Exceptions areFor ~ continued ~ To force you to handle Bad Things  because return codes can be tedious  and sometimes you’re lazy To signal errors from constructors  because constructors have no return value
  • 5.
    Example File I/O public FileReader(String fileName) throwsFileNotFoundException public void close() throws IOException
  • 6.
    import java.io.*; class OpenFile { publicstatic void main(String[] args) { if (args.length > 0) { try { // Open a file: FileReader f = new FileReader(args[0]); System.out.println(args[0] + " opened"); f.close(); } catch (IOException x) { System.out.println(x); } } } }
  • 7.
    What Exceptions areNOT For NOT For Alternate Returns:  e.g., when end-of-file is reached: while ((s = f.readLine()) != null) … Exceptions are only for the exceptional!
  • 8.
    Catching Exceptions Wrap codeto be checked in a try-block  checking occurs all the way down the execution stack try-blocks can be nested  control resumes at most enclosed matching handler
  • 9.
    Working of try-catch tryblock Statement that causes an exception Catch block Statement that handles the exception Throws exception object Exception object creator Exception handler
  • 10.
    Catching Exceptions ~ continued~ Place one or more catch-clauses after try- block  runtime system looks back up the call stack for a matching handler  subclass types match superclass types  catching Exception catches everything (almost)  handlers are checked in the order they appear  place most derived types first!  execution resumes after last handler  if you let it (could branch or throw)
  • 11.
    Multiple catch statements syntax: Try { Statement;//generates an exception } Catch(Exception type1 e) {Statement;} Catch(Exception type2 e1) {Statement;} …….. …….
  • 12.
    Throwing Exceptions Must throwobjects derived (ultimately) from Throwable Usually derive from java.lang.Exception The class name is the most important attribute of an exception Can optionally include a message  Provide two constructors:  MyException( )  MyException(String s)
  • 13.
    Throwing Exceptions ~ continued~ Control is passed up the execution stack to a matching handler Various methods exist for processing exceptions:  getMessage( )  toString( ) (class name + message)  printStackTrace( )
  • 14.
    Throwing Exceptions ~ continued~ Functions must “advertise” their exceptions  every function must specify the “checked” exceptions it (or its callees!) may throw Callers must do one of two things:  handle your exceptions with try-catch, or  advertise your exceptions along with theirs
  • 15.
    Standard Java Exceptions Throwable ExceptionError RuntimeException IOException . . .
  • 16.
    Class java.lang.Exception The oneyou usually derive from “Checked Exceptions”  specifications checked at compile time  you must either catch or advertise these  Used for recoverable errors  Not programmer errors
  • 17.
    java.lang.Exception Subclasses ~ sample~ AWTException ClassNotFoundException CloneNotSupportedException IOException NoSuchFieldException
  • 18.
    Class java.lang.Error For JVMFailures and other Weird Things  let program terminate InternalError is one of these Don’t catch them  you don’t know what to do! These are “unchecked exceptions”  not required to advertise
  • 19.
    java.lang.Error Subclasses AWTError LinkageError  … ThreadDeath VirtualMachineError InternalError, OutOfMemoryError, StackOverflowError, UnknownError
  • 20.
    Class java.lang.RuntimeException Stupid Name! Same as logic_error in C++ Program logic errors  e.g., bad cast, using a null handle, array index violation, etc.  Shouldn’t happen!  fixed during testing  Similar in spirit to C’s assert( ) macro  mainly for debugging These are called “unchecked exceptions”
  • 21.
    java.lang.RuntimeException Subclasses (sample) ArithmeticException (e.g.,divide by 0) ArrayStoreException ClassCastException IllegalArgumentException IndexOutOfBoundsException NullPointerException UnsupportedOperationException
  • 22.
    The finally Clause Forcode that must ALWAYS run  No matter what!  Even if a return or break occurs first  Exception: System.exit( ) Placed after handlers (if they exist)  try-block must either have a handler or a finally-block
  • 23.
    The finally Clause ~continued ~  The finally can be used to handle an exception (ie) not caught by any of the previous catch statement.  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. Syntax: try{ try{ …..} …..} finally{ catch(…){ ……} …..} finally{ ……}
  • 24.
    Exception-handling Syntax ~ TheWhole Picture ~ try { // normal code (conditionally executes) } catch (ExceptionType1 x) { // handle ExceptionType1 error } … catch (ExceptionTypeN x) { // handle ExceptionTypeN error } finally { // invariant code ("always" executes) }
  • 25.
    class FinallyTest { public staticvoid f() throws Exception { try { // 0 // return; // 1 // System.exit(0); // 2 // throw new Exception(); // 3a } catch (Exception x) { // throw new Exception(); // 3b } finally { System.out.println("finally!"); } System.out.println("last statement"); }
  • 26.
    public static voidmain(String[] args) { try { f(); } catch(Exception x) {} } }
  • 27.
    Program Output 0: finally! last statement 1: finally! 2: (nooutput) 3a: same as 0: 3a + 3b: compiler error (last statement not reachable)
  • 28.
    When to HandleExceptions Note: Manage.f( ) didn’t catch anything  wouldn’t know what to do if it did! You often let exceptions pass up the call stack Or you can re-throw in a catch  throw x; // in a handler where x was caught  or re-throw a new type of exception
  • 29.
    Exception Etiquette Don’t catchwhat you can’t (at least partially) handle  re-throw if only partially handled (“catch & release”: if you’re not going to eat it, throw it back!) Don’t catch & ignore  catch (Exception x){} // disables exceptions!
  • 30.
    How Exceptions Work Whenan exception is thrown execution backtracks up the runtime stack (list of active function invocations) Each stack frame contains information regarding local handlers, if any  Otherwise, execution returns up to the next caller, looking for a suitable catch What happens if there isn’t a matching catch?
  • 31.
    Uncaught Exceptions What ifthere is no handler for an exception? The thread dies!  exceptions belong to a thread (stack-specific)
  • 32.
    Throwing our ownExceptions Syntax: Throw new throwable_subclass; Ex: Throw new Arithmetic Exception();
  • 33.
    Program import java.lang.Exception; class myextends Exception { my(String msg);} class test { public static void main(String a[]) { int x=5,y=1000; try {float z=(float) x / (float) y; if(z<0.01) { throw new my(“Number is to small”); } } Catch(my e) { S.o.p(“Caught my exception”); S.o.p(“e.getMessage()); }
  • 34.
    ~ continued ~ Finally {S.o.p(“I am always here”); } } } O/P: Caught my exception Number is to small I am always here

Editor's Notes

  • #16 Throwable is a class.
  • #19 Errors can be caught, but shouldn’t be.