Professional Documents
Culture Documents
Lec24-Exception Handling
Lec24-Exception Handling
Lecture 24
Based on Slides of Dr. Norazah Yusof
1
Syntax Errors, Runtime Errors, and
Logic Errors
• There are three categories of errors:
• syntax errors,
• runtime errors, and
• logic errors.
• Syntax errors arise because the rules of the language
have not been followed. They are detected by the
compiler.
• Runtime errors occur while the program is running if the
environment detects an operation that is impossible to
carry out.
• Logic errors occur when a program doesn't perform the
way it was intended to.
2
Exception
• Exception is a runtime error.
• A program that does not provide code for catching and handling
exceptions will terminate abnormally, and may cause serious
problems.
• Exceptions occurs for various reasons:
• User enters an invalid input.
• Program attempt to open a file that doesn’t exist.
• Network connection may hang up,
• Program attempt to access an out-of-bounds array element
• and many more…
3
Uncaught Exceptions
• When an exception is thrown, it cannot be ignored.
• It must be handled by the program, or by the default
exception handler.
• When the code in a method throws an exception:
• normal execution of that method stops, and
• the JVM searches for a compatible exception handler inside
the method.
4 4
Runtime Errors
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
5
Exception – stack trace
• Several information are displayed in response to the invalid
input.
6
Exception – stack trace
7
Catch Runtime Errors
1 import java.util.*;
2 public class Example1b{
3 public static void main(String args[]) {
4 Scanner scanner = new Scanner(System.in);
5 try {
6 System.out.println ("Enter an integer:");
7 int num = scanner.nextInt();
8 System.out.println ("The number entered is:"+
If an exception
occurs on this
9 num);
line, the rest of 10 }
lines in the try 11 catch (InputMismatchException ex) {
block are 12 System.out.println ("Try again ("+
skipped and the
control is 13 "Error input: an integer number is required)");
transferred to 14 scanner.nextLine(); //discard input
the catch block. 15 }
16 }
}
8
Exception handling
9
Exception Classes
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
10
Exception Classes
• The exception classes can be classified into three
major types:
1. System errors
2. Exceptions
3. Runtime exceptions
11
System Errors
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
12
Exceptions
Exception describes errors ClassNotFoundException
caused by your program
and external IOException
circumstances. These ArithmeticException
errors can be caught and Exception AWTException
handled by your program. NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
13
Runtime Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
15 15
Unchecked Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError Unchecked
Error exception.
AWTError
16
Unchecked Exceptions
• These exceptions can be avoided with properly written
code.
• With an unchecked exception, however, compiler
doesn't force client programmers either to catch the
exception or declare it in a throws clause.
• All exceptions that are not derived from Error or
RuntimeException are checked exceptions.
17 17
Unchecked Exceptions
• Is any exception belonging to a subclass of
RuntimeException.
• It is not checked by the compiler and can occur anywhere in the
program.
• In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable.
• For example,
• a NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to
it;
• an IndexOutOfBoundsException is thrown if you access an
element in an array outside the bounds of the array.
18
Checked Exceptions
• Is one that can be analyzed by the Java compiler (JVM).
• Checked exceptions are thrown by methods such as the
BufferedReader.readLine() method.
• When compiler encounters one of these method calls, it
checks whether the program either handles or declares the
exception.
• Compile-time checking for these exceptions is designed to
reduce the number of exception that are not properly
handled within a program.
19
Checked Exceptions
• A checked exception is any subclass of Exception (or Exception
itself), excluding class RuntimeException and its
subclasses.
• You should compulsorily handle the checked exceptions in your
code, otherwise your code will not be compiled. i.e you should
put the code which may cause checked exception in try block.
"checked" means they will be checked at compile time itself.
• There are two ways to handle checked exceptions. You may
declare the exception using a throws clause or you may use the
try..catch block.
• The most perfect example of Checked Exceptions is
IOException which should be handled in your code
Compulsorily or else your Code will throw a Compilation Error.
20 20
Checked Exceptions
// This method will not compile!
public static void main(String args[]){
BufferedReader input = new BufferedReader
(new InputStreamReader(System.in));
String inputData;
int num;
System.out.println ("Enter an integer:");
inputData = input.readLine();
num = Integer.parseInt(inputData);
System.out.println ("The square is:" +
(num*num));
}
21 21
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or RuntimeException),
you must invoke it in a try-catch block or declare to throw the exception in
the calling method.
For example, suppose that method p1 invokes method p2 and p2 may throw
a checked exception (e.g., IOException), you have to write the code as shown
in (a) or (b).
(a) (b)
22
Checked Exceptions
23 23
• OR:
//program 11.2b
import java.io.*;
public class Example2 {
public static void main(String args[]) throws
IOException {
BufferedReader input = new BufferedReader (new
InputStreamReader(System.in));
String inputData;
int num;
System.out.println ("Enter an integer:");
inputData = input.readLine();
num = Integer.parseInt(inputData);
System.out.println ("The square is:"+(num*num));
}
}
24 24
• OR:
//program 11.2c
import java.io.*;
public class Example3 {
public static void main(String args[]) {
try {
BufferedReader input = new BufferedReader (new
InputStreamReader(System.in));
String inputData;
int num;
System.out.println ("Enter an integer:");
inputData = input.readLine();
num = Integer.parseInt(inputData);
System.out.println ("The square is:"+(num*num));
}
catch (NumberFormatException ex) {
System.out.println ("Wrong data type");
}
catch (IOException ex){
System.out.println ("input problem");
}
}
}
25 25
Exception Handler in the method where it occurs
try
{
//the code which will cause the exception
}
catch(SomeExceptionType ex)
{
//the code which will handle an object of that //exception
class
}
:://more catch blocks
catch(AnotherExceptionType ex)
{}
finally
{//the code which will always executed}
//Statements following the structure
26 26
Exception Handler in the method where it occurs
27 27
How try, catch{} & finally{} works
Pick best match No
Match
} } } } Execution
leaves this
method
No Exception
finally
{
28 28
Self test 1
1 import java.io.*;
2 public class TestException {
3 public static void main (String[] args) throws
4 IOException {
5 try {
6 method();
7 System.out.println("After method call");
8 }
9 catch (ArithmeticException ex ){
10 System.out.println("ArithmeticException");
11 }
12 catch (RuntimeException ex ){
13 System.out.println("RunTimeException");
14 }
15 catch (Exception ex ){
16 System.out.println("Exception");
17 }
18 }
19 //static method function
20 }
29
Self test 2
What is displayed on the screen, if the body of
method() is given as follows:
30
Self test 3
What is displayed on the screen, if the body of
method() is given as follows:
1 static void method() throws Exception {
2 try{
3 String s="abc";
4 System.out.println(s.charAt(3));
5 }
6 catch (RuntimeException ex ){
7 System.out.println("RunTimeException in method()");
8 }
9 catch (Exception ex ){
10 System.out.println("Exception in method()");
}
11
31
Rules
• A program CANNOT have more than one catch
clause per exception type in the same try statement.
• If you are handling multiple exceptions in the same try
statement, then you MUST handle the more
specialized exception classes before the more
general exception classes.
• The finally block is an option block that can appear
after all the catch blocks.
32 32
Propagate the Exception Handler in
different method
33
Propagate the Exception Handler in different method
public class Pd
{ public void metod1(int i, int j)
{ try
{metod2(i,j); }
catch(ArithmeticException e)
{ System.out.println("i=" +i+ "\tj=" +j);
e.printStackTrace();
System.out.println("This is your problem:" +e.getMessage());
} }
public void metod2(int i, int j) throws ArithmeticException
{ System.out.println("metod2 bermula");
j = i/j;
System.out.println("metod2 berakhir");}
35
Declaring Exceptions
• Every method must state the types of checked exceptions it
might throw.
• This is known as declaring exceptions.
• To declare an exception in a method, use the throws
keyword:
36
Declaring Exceptions - Example
1 import java.io.*;
2
3 public class Example2 {
4 public static void main(String args[]) throws IOException {
5 BufferedReader input = new BufferedReader (new
InputStreamReader(System.in));
6 String inputData;
7 int num;
8
9 System.out.println ("Enter an integer:");
10 inputData = input.readLine();
11 num = Integer.parseInt(inputData);
12 System.out.println ("The square is:"+(num*num));
13 }
14 }
37
Throwing Exceptions
• When the program detects an error, the program can
create an instance of an appropriate exception type and
throw it.
• This is known as throwing an exception. Here is an
example,
38
Throwing Exceptions Example
1 public class CalcRadius
2 {
3 double radius;
4 public void setRadius(double newRadius)
5 throws IllegalArgumentException {
6 if (newRadius >= 0)
7 radius = newRadius;
8 else
9 throw new IllegalArgumentException(
10 "Radius cannot be negative");
11 }
12 public double getRadius(){
13 return radius;
14 }
15 }
39
Throwing Exceptions Example
1 import java.util.*;
2
3 public class CalcRadiusTest {
4 public static void main(String args[]) {
5 try {
6 Scanner input = new Scanner(System.in);
7 System.out.println ("Input a radius =");
8 double data = input.nextDouble();
9 CalcRadius rad = new CalcRadius();
10 rad.setRadius(data);
11 System.out.println ("Radius =" + rad.getRadius());
12 }
13 catch (IllegalArgumentException e) {
14 System.out.println (e.getMessage());
15 e.printStackTrace();
16 System.exit(0);
17 }
18 }
19 }
40
Example: Declaring, Throwing, and
Catching Exceptions
• Objective: This example demonstrates declaring,
throwing, and catching exceptions by modifying the
setRadius method in the Circle class defined in
Chapter 6.
• The new setRadius method throws an exception if
radius is negative.
41
Self test 1
1 public class TestEx1 {
2 public static void main(String args[]){
3 for (int i=1; i<2; i++)
4 System.out.println(i + " ");
5 try {
6 System.out.println(1/0);
7 }
8 catch (Exception ex){
9 System.out.println("Tiada operasi");
10 }
11 }
12
}
42
Self test 2
1 public class TestEx2 {
2 public static void main(String args[]){
3 try {
4
for (int i=2; i>=0; i--) {
5
6 System.out.print("1 / "+ i + " = ");
7 System.out.println(1/i);
8 }
9 }
10 catch (Exception ex){
11
12 System.out.println("Infiniti");
13 }
14 }
15
16 }
43
Catching Exceptions
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
44
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
45
Order of the Exception Handling
46
Wrong Order of the Exception Handling
try{
. . .
}
catch (Exception ex){
…
}
catch (RunTimeException ex){
…
}
RunTimeException class is a subclass of Exception. Error occurs because
superclass appears before a catch clause for the subclass type.
47
Correct Order of the Exception Handling
try{
. . .
}
catch (RunTimeException ex){
…
}
catch (Exception ex){
…
}
48
Cautions When Using
Exceptions
• Exception handling separates error-handling code from
normal programming tasks, thus making programs
easier to read and to modify.
• Be aware, however, that exception handling usually
requires more time and resources because it requires
• instantiating a new exception object,
• rolling back the call stack, and
• propagating the errors to the calling methods.
49
When to Throw Exceptions
• An exception occurs in a method.
• If you want the exception to be processed by its caller,
you should create an exception object and throw it.
• If you can handle the exception in the method where it
occurs, there is no need to throw it.
50
When to Use Exceptions
When should you use the try-catch block in the code? You should
use it to deal with unexpected error conditions. Do not use it to
deal with simple, expected situations. For example, the following
code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
} 51
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
52
Creating Custom Exception Classes
53
Creating your own Exception class
Steps:
a) Define the Exception class as a subclass to the Exception class:
public class MyException extends Exception
b) Build a constructor
public MyException(int i)
{
value = i;
}
d) Steps a)+ b) + c)
54
Overall Picture
Exception
MyException
55
public class MyException extends Exception {
private int value;
private String message;
public MyException(int i) {
value = i;
message = new String("MyException occurs at value: " +
value);
}
public String getMessage() {
return message;
}
}
56
How to use the user-defined exceptions?