You are on page 1of 33

1

Exception
Handling

DR. RAMESH KUMAR,


ASSISTANT PROFESSOR, ELECTRONIC ENGINEERING
DEPARTMENT
DAWOOD UET, KARACHI
Motivation 2
 When a program runs into a runtime error, the program terminates
abnormally.
 Runtime errors occur while a program is running if the JVM detects an
operation that is impossible to carry out.
 ArrayIndexOutOfBoundsException & InputMismatchException etc.
 How can you handle the runtime error so that the program can
continue to run or terminate gracefully?

Exception
 Unexpected conditions
 Disrupt normal flow of program
 With exception handling, we can develop more robust programs
 Exceptions are thrown And can be caught
Programming Errors 3

 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.
Run-time Errors 4

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
10 System.out.println(
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
Quotient Program 5

import java.util.Scanner;
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(number1 + " / " + number2 + " is
" +
(number1 / number2));
}
}
Quotient Program
6
import java.util.Scanner;
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(number1 + " / " + number2 + " is
" +
(number1 / number2));
}
}
Quotient Program
7
import java.util.Scanner;
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(number1 + " / " + number2 + " is
" +
(number1 / number2));
}
}
Quotientif Program 8

import java.util.Scanner;
public class QuotientWithIf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
if (number2 != 0)
System.out.println(number1 + " / " + number2 + "
is " +
(number1 / number2));
else
System.out.println("Divisor cannot be zero ");
}
}
Quotientif Program 9
import java.util.Scanner;
public class QuotientWithMethod {
public static int quotient(int number1, int number2) {
if (number2 == 0) {
System.out.println("Divisor cannot be zero");
System.exit(1);
}
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is "
+ result); } }
Exception Types 10
System Errors 11

ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


System errors are thrown by JVM
and represented in the Error class. LinkageError
The Error class describes internal
system errors. Such errors rarely Error VirtualMachineError
occur. If one does, there is little
you can do beyond notifying the
Many more classes
user and trying to terminate the
program gracefully.
Exceptions 12

Exception describes errors ClassNotFoundException


caused by your program and
ArithmeticException
external circumstances. These IOException
errors can be caught and
Exception NullPointerException
handled by your program.
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes


Run-time Exception 13

ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError
Runtime Exception is caused by
programming errors, such as bad
Error VirtualMachineError casting, accessing an out-of-bounds
array, and numeric errors.
Many more classes
Declaring, Throwing, and 14

Catching Exceptions

method1() { declare exception


method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}
Declaring Exception 15

 Every method must state the types of checked


exceptions it might throw
 This is known as declaring exceptions.

 public void myMethod() throws IOException


 public void myMethod() throws IOException,
OtherException
Throwing Exception 16

 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;
Throwing Exception Example 17

/** Set a new radius */


public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
When to throw Exception 18
 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.
Catching Exception 19
try {
Code to run;
A statement or a method that may throw an exception;
More code to run;
}
catch (type ex) {
Code to process the exception;
}
Multiple Catch Conditions 20
public class Test {
public static void main(String[] args) {
try {
int[] list = new int[10];
System.out.println("list[10] is " + list[10]);
}
catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
}
catch (IndexOutofBoundsException ex) {
System.out.println(" IndexOutofBoundsException");
}
catch (Exception ex) {
System.out.println("Exception");
} } }
Catching Exceptions 21

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

Call Stack
method3

method2 method2

method1 method1 method1

main method main method main method main method


The finally Clause 22

try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Trace a Program Execution 23

Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution 24

try {
statements;
}
catch(TheException ex) {
The final block is
handling ex; always executed
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution 25

try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
The Next statement
finalStatements; is executed
}

Next statement;
Trace a Program Execution 26

try { Suppose an exception


statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution 27

try { The exception is


statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution 28

try { The final block is


statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
Trace a Program Execution 29

try { The next statement in


statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;
import java.util.Scanner;
public class QuotientWithException {
public static int quotient(int number1, int number2) {
if (number2 == 0)
30
throw new ArithmeticException("Divisor cannot be zero");
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is " + result);
}
catch (ArithmeticException ex) {
System.out.println("Exception: an integer " +
"cannot be divided by zero ");
}
System.out.println("Execution continues ...");
}
}
31
Exception-Handling Example
32
Exception-Handling Example
33

You might also like