0% found this document useful (0 votes)
32 views

Exception Handling

The document discusses Java's exception handling mechanisms including try/catch blocks, throwing exceptions, and the Throwable class hierarchy. It describes how exceptions indicate runtime errors, the different exception types like Error and Exception, and how exceptions propagate through the call stack and can be caught and handled.

Uploaded by

Oscar Mok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Exception Handling

The document discusses Java's exception handling mechanisms including try/catch blocks, throwing exceptions, and the Throwable class hierarchy. It describes how exceptions indicate runtime errors, the different exception types like Error and Exception, and how exceptions propagate through the call stack and can be caught and handled.

Uploaded by

Oscar Mok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Exception Handling

Outline
Introduction
Java’s way
Try blocks
Throwing an exception
Catching an exception
Throwable
Chained exceptions

2
Introduction (1/4)
Exceptions
Indicate that a problem (runtime error) occurred during the
program’s execution
e.g. divide by zero, array index out of bounds
Exception
Superclass of all exceptions
Recover from exception handlers
Events might be ignored if no listener registered
From C++
Take the style and details of exception handling from C++
3
Introduction (2/4)
Fig 11.1
Divide by zero without exception handling
Scanner
A simple text scanner which can parse primitive types and
strings using regular expressions
Break its input into tokens using a delimiter pattern, which by
default matches whitespace
Scanner(System.in)
nextByte(), nextInt(), nextShort(), nextLong(), nextBoolean(),
nextFloat(), nextDouble()

nextBoolean()

next(), nextLine()
4
Introduction (3/4)

Stack trace
Name of the exception in a descriptive message that
indicates the problem
Complete method-call stack

Please enter an integer numerator: 40 Stack Frame


Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:10)
at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:22)

Stack Trace Element


5
Introduction (4/4)
ArithmeticException
Thrown when an exceptional arithmetic condition has
occurred. For example, an integer "divide by zero" throws
an instance of this class
InputMismatchException
Thrown by a Scanner to indicate that the token retrieved
does not match the pattern for the expected type

6
Java’s Way (1/4)

Four operations
Restrict the handling area
Claim an exception
Tell the compiler what can go wrong
Throw an exception
Create an exception object and pass it to the system
Catch an exception
Find an exception handler

7
Java’s Way (2/4)
Fig. 11.2
Restrict the handling area
try { …… }
claim an exception
int quotient(int numerator, int denominator) 

throws ArithmeticException
throw an exception
numerator/denominator //if (denominator==0)
automatically throw new ArithmeticException()

8
Java’s Way (3/4)
catch an exception
catch (InputMismatchException) { … }

catch (ArithmeticException) { … }
scanner.nextLine()
Advance this scanner past the current line and return the
input that was skipped
Read the current line

9
Java’s Way (4/4)
Advantages of handling exceptions
Clearer
Programmer’s reading code can easily determine if the
proper error checking has been implemented
Separate the error handling code from the “main line” of
program code
Rather than coding error handler in the methods
Let programmers provide customized error messages
More robust
Avoid the unconditional termination of running programs

10
Try Block (1/8)
Restrict the handling area
Format
try {

…

}

catch (ExceptionType ref) { … }

…

finally { … }

next_statement
zero or more catch blocks
finally block is optional
If there are no catch blocks following a try block, the finally
block is required
11
Try Block (2/8)
try {

…

Control flow }

catch (ExceptionType ref) { … }

IF (an exception is thrown) {
 …

IF (a local catch block is found) {
 finally { … }

the catch block
 next_statement
finally block

next_statement

} ELSE {

finally block

find an appropriate handler through call chain

(terminate non-GUI program if nothing caught) } 

} ELSE { 

finally block

next_statement }
12
Try Block (3/8)

It is a syntax error to place code between a try block


and its corresponding catch blocks

13
Try Block (4/8)
Fig. 11.5
throw statement
throw exceptionObject
衍⽣生
exceptionObject belongs to any class derived from
Throwable
It happens within the try block
Re-throw an exception
Make a throw statement within the catch block
Re-throw the exception to the next enclosing try block

14
Try Block (5/8)
Throws clause
returnType fun(args) throws aaa { ….. }
It can throw objects of exceptionType aaa or aaa’s
subclasses
It can specify more than one exceptionTypes
e.g. int g(float h) throws aaa, bbb, ccc {..... }

15
Try Block (6/8)
catch (ExceptionType et) { … }
Associated with try block immediately before
Cannot access objects defined in the corresponding try block
One catch block handles only one exception
Search the first catch block in order
Catch all objects of subclasses of declared exception
Order your catch blocks carefully
Syntax error:

A catch block that catches a superclass object is placed
before a catch block for that class’s subclass types
16
Try Block (7/8)
catch (Exception e) { … }
catch all exceptions
Usually treat it as an “otherwise”
Must be placed at the last, or a syntax error occurs
ERROR MESSAGE: Exception XXX has already been
caught.

17
Try Block (8/8)
finally block
always executed even if
no exception occurs
exit try block via a return, break or continue
Re-throw an exception in a catch block
execute finally block first, and then pass exception up
the call chain
Optional
Usage
Releasing resources acquired in its try block
e.g. close files opened in the try block
Usually not to throw another exception

18
Throwable (1/9)

19
Throwable (2/9)

Error class or Exception class


Error class
Indicate serious problems that a reasonable application
should not try to catch
Most such errors are abnormal conditions

20
Throwable (3/9)
Exception class
Indicate conditions that a reasonable application might want
to catch
IOException
These are all checked exceptions that can occur during
input/output and file processing
RuntimeException
Superclass of those exceptions that can be thrown during the
normal operation of the Java Virtual Machine

21
Throwable (4/9)
Object ß Throwable

ß Error

ß LinkageError

ß ThreadDeath

ß VirtualMachineError

ß AWTError

ß Exception

ß IOException

ß FileNotFoundException

ß EOFException

ß MalformURLException

ß ProtocolException

ß SocketException

ß ConnectException

ß NoRouteToHostException

ß UnknownHostException

22
Throwable (5/9)
Object ß Throwable

ß Exception

ß ClassNotFoundException

ß InstantiationException

ß NoSuchMethodException

ß RuntimeException

ß ArithmeticException

ß ArrayStoreException

ß ClassCastException

ß IllegalArgumentException

ß IllegalThreadStateException

ß NumberFormatException

ß IndexOutOfBoundsException

ß ArrayIndexOutOfBoundsException

ß StringIndexOutOfBoundsException

ß NegativeArraySizeException

ß NullPointerException
23
Throwable (6/9)
Claiming an Exception
Unchecked Exception
e.g. Error, RuntimeException
Not necessary to claim
Checked Exception
e.g. IOException
A method’s checked exception need to be listed in that
method’s throws clause
Syntax error if not claim
If your method calls other methods that explicitly throw
checked exceptions, those exception must be listed in the
throws clause of your method, unless your method catches
those exception.
24
Throwable (7/9)
Fig. 11.6
Throwable
public Throwable(String errorMessage)
Exception (String errorMessage)
public Throwable()
Constructs a new throwable with null as its detail message
String getMessage()
Return user-defined “errorMessage”; or null if none

25
Throwable (8/9)
String printStackTrace()
Output stack frames to the standard error stream
The top of the stack frame is the last method invocation in
the sequence
Testing and debugging
StackTraceElement[] getStackTrace()
Provides programmatic access to the stack trace information
printed by printStackTrace()
The zeroth element of the array represents the top of the
stack

26
Throwable (9/9)
StackTraceElement
Each element represents a single stack frame
All stack frames except for the one at the top of the stack
represent a method invocation
String getClassName()
String getFileName()
String getMethodName()
int getLineNumber()

27
Chained Exceptions
Fig. 11.7
public Exception(String message, Throwable cause)
public Exception(String message)
The cause is not initialized

28

You might also like