Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

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.

• This information is known as stack trace, that include:


• The name of the exception,
• The method call stack

6
Exception – stack trace

• From the last line of the stack trace:


• The exception was detected at line 8 of the main method, contains the class name and
method (Example1b.main) along with the filename and and line number
(Example1b.java:8)
• Moving up the stack:
• The exception occurred at line 2000 in the nextInt method of the Scanner class.
• The exception occurred at line 2040 in the overloaded nextInt method of the Scanner
class.
• The exception occurred at line 1431 in the next method of the Scanner class.
• The exception occurred at line 819 in the throwFor method of the Scanner class.
• The last method in the call chain actually threw an InputMismatchException.

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

• The try-block contains the statements that might


throw exceptions.
• The catch-block handles the exceptional case. The
catch-block takes a parameter of type Exception.
• When a statement in the try-block throws an
exception, the execution in the try-block ends and
control passes to the catch-block(s).

9
Exception Classes
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

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

LinkageError Several more classes

System errors are thrown by JVM


and represented in the Error class. VirtualMachineError
The Error class describes internal Error
system errors. Such errors rarely AWTError
occur. If one does, there is little
you can do beyond notifying the Several more classes
user and trying to terminate the
program gracefully.

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

LinkageError Several more classes


Example:
1. Class not found
2. Clone not VirtualMachineError
supported Error
3. Related AWTError
input/output
operations
Several more classes

13
Runtime Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError RuntimeException is caused by


Error programming errors, such as bad
casting, accessing an out-of-
AWTError
bounds array, and numeric
errors.
Several more classes This exceptions are generally
thrown by the JVM.
They are known as unchecked
14
exceptions.
Checked and Unchecked Exceptions
• There are two categories of exceptions:
• unchecked
• checked.
• Unchecked exceptions are those that are derived from the
Error class or the RuntimeException class.
• Exceptions derived from Error are thrown when a
critical error occurs, and should not be handled.
• RuntimeException serves as a superclass for
exceptions that result from programming errors.

15 15
Unchecked Exceptions

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError Unchecked
Error exception.
AWTError

Several more classes

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).

void p1() { void p1() throws IOException {


try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}

(a) (b)
22
Checked Exceptions

• The code in this method is capable of throwing checked


exceptions.
• Ways to solve:
• Either:
• The keyword throws can be written at the end of the method
header, followed by a list of the types of exceptions that the method
can throw.

public static void main(String args[]) throws


IOException {

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

• The normal case is handled in a try-block.


• The exceptional case is handled in a catch-
block.
• The catch-block takes a parameter of type
Exception.
• If an exception is thrown, execution in the try-
block ends and control passes to the catch-
block(s) after the try-block

27 27
How try, catch{} & finally{} works
Pick best match No
Match

try catch catch catch


{ { { {

} } } } 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:

1 static void method() throws Exception {


2 System.out.println(1/0);
3 }

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");}

public static void main (String[] a)


{ Pd p = new Pd();
p.metod1(1,1); // no exceptions occur
p.metod1(1,0); // exception applies in method2 }}
34
3 Operations

Java’s exception handling model is based


on three operations:
Declaring an exception
Throwing an exception
Catching an exception

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:

public void myMethod() throws IOException

public void myMethod()


throws IOException, OtherException

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,

throw new TheException();

TheException ex = new TheException();


throw ex;

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

• The order of which exceptions are specified in catch clauses


is important.
• Compilation error will result if a catch clause for a
superclass type appears before a catch clause for a subclass
type.
• For example:

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){

}

RunTimeException class is a subclass of Exception.

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

 Use the exception classes in the API whenever possible.


 Create custom exception classes if the predefined
classes are not sufficient.
 Declare custom exception classes by extending
Exception or a subclass of Exception.

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;
}

c) Override a super class method


public String getMessage()
{
return message;
}

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?

public class Propagate {


public void method1(int i) {
try {
method2(i);
}
catch(MyException e) {
System.out.println(e.getMessage());
} }
  public void method2(int i) throws MyException {
if(i == 1)
throw new MyException(i);
else {
method3(i);
} }
  public void method3(int i) throws MyException {
if(i == 0)
throw new MyException(i);
else
System.out.println("i = " + i);
}
public static void main(String[] args) {
Propagate p = new Propagate();
for (int i = 0; i < 3; i++)
p.method1(i); }} 57

You might also like