Exceptions
(http://docs.oracle.com/javase/tutorial/essential/
exceptions/index.html)
Objectives
• Exception Handling
– try block
– catch block
– finally block
– custom exception class
Exceptions
• Exception: Error beyond the control of a program. When
an exception occurs, the program will terminate abruptly.
• When a program is executing something occurs that is
not quite normal from the point of view of the goal at
hand.
• For example:
– a user might type an invalid filename;
– An accessed file does not exist of might contain corrupted data;
– a network link could fail;
– …
• Circumstances of this type are called exception
conditions in Java and are represented using objects (All
exceptions descend from the java.lang.Throwable).
Exceptions
• Three types of errors
• Syntax errors Easiest to detect and correct
• Occurs when the rule of the language is violated
• Detected by compiler
• Run-time errors
• Occurs when the computer detects an operation that
cannot be carried out (eg: division by zero; x/y is
syntactically correct, but if y is zero at run-time a run-
time error will occur)
Hardest to detect and correct
• Logic errors
• Occurs when a program does not perform the
intended task
Exceptions
• The following program causes an exception.
Exceptions Exceptions are pre-defined data
(Exception classes) thrown by
JVM and they can be caught by
code in the program
Exceptions
• Consider the factorial() method:
• What if the caller supplies a negative parameter?
public static int factorial(int n) {
int ans = 1;
for (int i = 2; i <= n; i++) ans *= i; What if n is negative?
return ans;
}
Should we terminate the program?
public static int factorial(int n) {
if (n < 0) { System.exit(n) terminates
System.out.println("n is negative"); the program with exit code n.
System.exit(1); In UNIX, you can check the exit
} code immediately after the
//Other code not changed program is terminated, with this
} command: echo $?
Note that factorial() method can be used by other programs
Hence, difficult to cater to all possible scenarios
Exceptions
• Instead of deciding how to deal with an error, Java
provides the exception mechanism:
1. Indicate an error (exception event) has occurred
2. Let the user decide how to handle the problem in a separate
section of code specific for that purpose
3. Crash the program if the error is not handled
• Exception mechanism consists of two components:
• Exception indication
• Exception handling
• Note that the preceding example of using exception for
(n < 0) is solely illustrative. Exceptions are more
appropriate for harder to check cases such as when
the value of n is too big, causing overflow in
computation.
Exceptions
• To indicate an error is detected:
• Also known as throwing an exception
• This allows the user to detect and handle the error
throw ExceptionObject;
SYNTAX
Exception object must be:
An object of a class derived from class Throwable
Contain useful information about the error
There are a number of useful predefined exception classes:
ArithmeticException
NullPointerException
IndexOutOfBoundsException
IllegalArgumentException
Exceptions
• The different exception classes are used to
categorize the type of error:
• There is no major difference in the available methods
Constructor
ExceptionClassName(String Msg)
Construct an exception object with the error message Msg
Common methods for Exception classes
String getMessage()
Return the massage stored in the object
void printStackTrace()
Print the calling stack
Exceptions
public static int factorial(int n)
throws IllegalArgumentException {
This declares that method factorial()
if (n < 0) { may throw IllegalArgumentException
IllegalArgumentException exObj
= new IllegalArgumentException(n + " is invalid!");
throw exObj;
}
Actual act of throwing an exception (Note: ‘throw’ and not ‘throws’ ).
These 2 statements can be shortened to:
throw new
IllegalArgumentException(n + " is invalid!");
int ans = 1;
for (int i = 2; i <= n; i++)
ans *= i;
return ans;
}
• Note:
• A method can throw more than one type of exception
Kinds of Exceptions
Checked Exceptions
(We must use the try
catch blocks or throw)
Unchecked- Exceptions
Program Bugs
Refer to the Java.lang documentation (We may not use the
try catch blocks)
for more information.
Two Kinds of Exception (1)
• Checked exception
– Must be handled by either the try-catch
mechanism or the throws-declaration
mechanism.
• Runtime exception
– The right time to deal with runtime exceptions
is when you’re designing, developing, and
debugging your code. Since runtime
exceptions should never be thrown in finished
code.
Two Kinds of Exception (2)
• Checked exceptions are those that require handling during
compile time, or a compilation error will occur.
• Unchecked exceptions are those whose handling is not
verified during compile time.
• RuntimeException, Error and their subclasses are
unchecked exceptions.
• In general, unchecked exceptions are due to
programming errors that are not recoverable, like
accessing a null object (NullPointerException),
accessing an array element outside the array bound
(IndexOutOfBoundsException), etc.
• As unchecked exceptions can occur anywhere, and to
avoid overuse of try-catch blocks, Java does not
mandate that unchecked exceptions must be handled.
Two Kinds of Exception (3)
• InputMismatchException and IllegalArgumentException
are subclasses of RuntimeException, and hence they
are unchecked exceptions. (Ref: ExampleImproved.java
and TestException.java)
[501043 Lecture 6: Exceptions]
Catching exceptions:
try catch finally (1)
try block try {
< statements may cause exceptions >
false }
e?
true catch ( ExceptionType1 e1 ) {
< statements handle the situation 1>
catch block }
catch ( ExceptionType2 e2) {
finally block < statements handle the situation 2>
}
finally {
If no exception is thrown < statements are always executed >
in the try block, all catch }
blocks are bypassed
If an exception arises, the first matching catch block, if any, is executed, and the
others are skipped
Catching exceptions:
try catch finally (2)
• Another version
• Keep retrying if n < 0
TestExceptionRetry.java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Enter n: -2
int input; -2 is invalid!
boolean retry = true; Enter n: -7
do { -7 is invalid!
try { Enter n: 6
System.out.print("Enter n: "); Ans = 720
input = sc.nextInt();
System.out.println("Ans = " + factorial(input));
retry = false; // no need to retry
} catch (IllegalArgumentException expObj) {
System.out.println(expObj.getMessage());
}
} while (retry);
}
[501043 Lecture 6: Exceptions]
Catching specific/general-level exception
Type conformity: father=son;
Throwing exceptions in methods
May we intentionally throw an exception? YES
Exception Propagations
catch(...)
A()
B()
Stack for A()
Stack for B() C()
Stack for C() D() Exception
Stack for D()
Stack trace When an exception occurs at a method, program
stack is containing running methods ( method A
calls method B,….). So, we can trace statements
related to this exception.
Exception
Propagations
Catching Exceptions…
Using try…catch to input an integer 10<=n<=50
Scanner in = new Scanner(System.in);
boolean cont = true;
int n;
do {
try {
System.out.print(“Enter a whole number: ");
a = Integer.parseInt(in.nextLine());
cont = false;
} catch (Exception e) {
System.out.println("Required integer!");
}
} while (cont == true|| n<10 || n>50);
The finally block (1)
• A try block may optionally have a finally block
associated with it.
• The code within a finally block is guaranteed to
execute no matter what happens in the
try/catch code that precedes it.
– The try block executes to completion without
throwing any exceptions whatsoever.
– The try block throws an exception that is handled by
one of the catch blocks.
– The try block throws an exception that is not
handled by any of the catch blocks
Nesting of try/catch Blocks
• A try statement may be nested inside either the try or
catch block of another try statement.
try {
// Pseudo code.
open a user-specified file
}
catch (FileNotFoundException e) {
try {
// Pseudo code.
open a DEFAULT file instead ...
}
catch (FileNotFoundException e2) {
// Pseudo code.
attempt to recover ...
}
}
Creating Your Own Exception Classes (1)
• Decide whether you want a checked or a
runtime exception.
– Checked exceptions should extend
java.lang.Exception or one of its subclasses.
– Runtime exceptions should extend
java.lang.RuntimeException or one of its
subclasses
Creating Your Own Exception Classes (2)
• New exception classes can be defined by deriving from class
Exception:
public class MyException extends Exception {
public MyException(String s) {
super(s);
}
}
The new exception class can then be used in throw statements
and catch blocks:
throw new MyException("MyException: Some reasons");
try {
...
} catch (MyException e) {
...
}
[501043 Lecture 6: Exceptions]
Exceptions and Overriding
• When you extend a class and override a
method, the Java compiler insists (đòi hỏi)
that all exception classes thrown by the
new method must be the same as, or
subclasses of, the exception classes
thrown by the original method.
Assertions
• Assertions are introduced in Java 1.4
• 2 Ways of writing assertion statements:
assert expression; // true-false condition
assert expression1:expression2; //
condiontion:ExceptionMessage
• You must specify options when the program is compiled
and run.
We can replace an assertion with an if statement.
In Java from 1.5, the keyword assert is removed.
Assertions…
Summary
• Exception Handling
• Multiple Handlers
• Code Finalization and Cleaning Up
(finally block)
• Custom Exception Classes
• Assertions