Professional Documents
Culture Documents
Exception Handling: CS F213: Object Oriented Programming
Exception Handling: CS F213: Object Oriented Programming
Dipanjan Chakraborty
Department of CS&IS
1
Exceptions in Java
●
Runtime errors in Java are called exceptions
●
Java includes mechanisms to handle exceptions at
runtime
– In some other languages, which lack exception
handling mechanisms, check for errors have to
be done manually using error codes
2
Exceptions in Java
●
When an exception occurs in a Java program, an
object representing the exception is created and
thrown in the method that caused the error
●
The method may choose to handle the exception
itself or pass it on
– At some point the exception will need to be caught
and processed
3
Exceptions in Java
●
Five keywords: try, catch, throw, throws, finally
●
try block: contains code that need to be tested for exceptions
●
catch block: handles the thrown exception in some rational manner
●
throw keyword: used to manually throw an exception
●
throws keyword: used to qualify a method in which an exception is
thrown
●
finally block: contains code that must be executed after a try block
●
System-generated exceptions are automatically thrown by the Java
run-time system
4
General format
1 try {
2 // block of code to monitor for errors
3 }
4 catch (ExceptionType1 exOb) {
5 // exception handler for ExceptionType1
6 }
7 catch (ExceptionType2 exOb) {
8 // exception handler for ExceptionType2
9 }
10 // ...
11 finally {
12 // block of code to be executed after try block ends
13 }
5
Hierarchy in Exceptions
6
Examples
●
Divide by zero
– Uncaught: caught by the default handler of the Java Runtime
System
– A stack trace is output sequencing the steps that led to the
exception
●
Catch the exception in a try-catch block
– What is the sequence of execution?
●
The goal of the catch block is to resolve the exceptional
condition and then continue as if the error had never happened
7
Try-Catch rules
●
try and catch statements form a unit
– A catch statement matches with the try block immediately
preceding the catch block
●
Statements protected by try must be included in curly braces
●
Modify the previous example to gracefully provide
information to the user
●
Use the toString() and printStackTrace() methods on the
exception object
8
More than one catch blocks
●
A try block may be followed by more than one catch block if more than one
exception can be executed by a single piece of code
●
When an exception is thrown, each catch statement is inspected in order, and
the first one whose type matches that of the exception is executed.
●
After one catch statement executes, the others are bypassed, and execution
continues after the try / catch block
●
If there are multiple catch statements, Exception subclasses must appear
before superclasses
– Unreachable code is an error in Java
●
Modify the previous programme to add code which can cause multiple
exceptions
9
Nested try statements
●
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
●
Method calls with try blocks, nested within a try block, are also implicitly
nested try statements
10
The throw statement
●
Programs can explicitly throw exceptions
– throw ThrowableInstance;
13
The finally statement
●
When Exceptions are thrown, methods might return prematurely
– Could be a problem, e.g. some methods might have opened a file
●
finally creates a block of code that will be executed after a try /catch block has
completedand before the code following the try/catch block
●
The finally block will execute whether or not an exception is thrown
●
If an exception is thrown, the finally block will execute even if no catch statement
matches the exception
●
Any time a method is about to return to the caller from inside a try/catch block, via
an uncaught exception or an explicit return statement, the finally clause is also
executed just before the method returns.
●
finally block is optional, but each try block requires at least one catch or finally
statement
14
Unchecked and Checked Exceptions
in Java
●
Unchecked Exceptions: Compiler does not
check if a method throws or handles these
exceptions (refer Table 10-1 in the textbook)
●
Checked Exceptions: must be included in the
throws list if the method does not handle them
itself (refer Table 10-2 in the textbook)
15
User Defined Exception Classes
●
Exception class can be inherited by custom exception
classes
●
Exception provides 4 public constructors. 2 of them
are:
– Exception()
– Exception(String msg)
●
One can override the methods in throwable (e.g.
toString()) in the custom exceptions
16
Chained Exception
●
What if an exception is caused by another error?
●
Two additional constructors used:
– Throwable(Throwable causeExc)
– Throwable(String msg, Throwable causeExc)
● causeExc is the underlying reason that an exception occurred
● Two methods available: Throwable
initCause(Throwable causeExc) and Throwable
getCause()
17
Additional Exception Features
●
Since JDK 7, three new features have been
added:
– try-with-resources (will be discussed later)
– multi-catch
– final rethrow or more precise rethrow
18
Multi-catch
●
Allows two or more exceptions to be caught by the
same catch clause
●
Two or more exception handlers may use the same
code sequence even though they respond to different
exceptions, instead of having to catch each exception
individually
●
e.g. catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
●
Each multi-catch parameter is implicitly final
19
More precise rethrow
●
Restricts the type of exceptions that can be
rethrown to:
– only those checked exceptions that the
associated try block throws
– that are not handled by a preceding catch clause
– and that are a subtype or supertype of the
parameter
20