Professional Documents
Culture Documents
Java Exception Notes
Java Exception Notes
• Typical problems
• try/catch; Catching Exceptions
• Checked and unchecked Exceptions
• throws, throw; Declaring and Throwing Exceptions
• (Writing own exception classes)
• Do’s and don’ts
• (Exercises next Tuesday)
A first example
public class Example1{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("The quotient is "+c);
}
}
Exceptions
When a Java program performs an illegal operation (division by zero,
access an array at a position which does not exist, etc) an event
known as exception happens. When an exception occurs, we say an
exception is thrown.
Examples:
• ArithmeticException, ArrayIndexOutOfBoundsException,
NumberFormatException
• IOException, FileNotFoundException, etc
Exceptions
When a Java program performs an illegal operation (division by zero,
access an array at a position which does not exist, etc) an event
known as exception happens. When an exception occurs, we say an
exception is thrown.
Examples:
• ArithmeticException, ArrayIndexOutOfBoundsException,
NumberFormatException
• IOException, FileNotFoundException, etc
Catching Exceptions
public class Example2 {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
try {
int quot = a / b;
System.out.println("The quotient is "+ quot);
}
catch (ArithmeticException e){
System.out.println("0 not allowed as 2nd input");
}
}
}
M. Seisenberger: CS-171, Spring 2006
6
Catching Exceptions
Remarks:
• Variables defined in the try block are only local.
Better: Define and initialise the variables outside the try block.
Valid inputs
Note that in the preceeding example, the Arithmetic Exception can be
avoided by using a case distinction.
More difficult it will be when we deal with user input and the question
whether a valid number has been entered. Here, definitely exception
handling is appropriate.
try {
a = Integer.parseInt(str)
}
catch (NumberFormatException e){
// Handle exception
}
finally
Occasionally you need to take some action whether or not an
exception is thrown. E.g. you have opened a file, an exception occurs
and you want to close the file first before dealing with the exception.
When the try block is completed, then the finally block will be
M. Seisenberger: CS-171, Spring 2006
15
executed. If an error occurs while reading the data, then first the
finally block will be executed, i.e. the file is closed and then the
exception is passed to its handler.
Similarly, we can catch an exception, do some action, then then
‘rethrow’ the exception.
try{
<statements>
}
catch (AnException e){
<do some actions>
throw e;
}