Java exceptions allow programs to handle and recover from errors and unexpected conditions. Exceptions are thrown when something abnormal occurs and the normal flow of execution cannot continue. Code that may throw exceptions is wrapped in a try block. Catch blocks handle specific exception types. Finally blocks contain cleanup code that always executes regardless of exceptions. Common Java exceptions include IOException for I/O errors and NullPointerException for null reference errors. Exceptions bubble up the call stack until caught unless an uncaught exception causes thread termination.
2. Outline
What exceptions are for
What exceptions are NOT for
Catching & Throwing exceptions
Exception Specifications
Standard Java Exceptions
The finally clause
Uncaught Exceptions
3. 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)
4. 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
6. 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);
}
}
}
}
7. 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!
8. 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
9. 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
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)
12. 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)
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
16. 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
18. 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
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”
22. 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
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{
……}
28. 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
29. 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!
30. 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?
31. Uncaught Exceptions
What if there is no handler for an
exception?
The thread dies!
exceptions belong to a thread (stack-specific)
32. Throwing our own Exceptions
Syntax:
Throw new throwable_subclass;
Ex:
Throw new Arithmetic Exception();
33. 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()); }
34. ~ continued ~
Finally
{ S.o.p(“I am always here”);
} } }
O/P:
Caught my exception
Number is to small
I am always here