KEMBAR78
Exception Handling inJava Programming.pptx
Divyavani, Assistant Professor 1
Divyavani, Assistant Professor 2
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
Exception Handling in Java
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
Exception is an unwanted or unexpected event, which occurs during the execution of a program,
i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the exception
object. It contains information about the exception, such as the name and description of the
exception and the state of the program when the exception occurred.
Divyavani, Assistant Professor 3
Major reasons why an exception Occurs:
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
differences between Error and Exception
Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Divyavani, Assistant Professor 4
Exception-Handling Fundamentals
 A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
 When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error.
 That method may choose to handle the exception itself, or pass it on. Either way, at some
point, the exception is caught and processed.
 Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code.
Divyavani, Assistant Professor 5
 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
 Program statements that you want to monitor for exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and handle it in some rational manner.
 System-generated exceptions are automatically thrown by the Java run-time system.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws clause.
 Any code that absolutely must be executed after a try block completes is put in a finally
block.
Divyavani, Assistant Professor 6
1. try: The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch: The catch block is used to handle the uncertain condition of a try block. A try block
is always followed by a catch block, which handles the exception that occurs in the
associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
Divyavani, Assistant Professor 7
3. throw: The throw keyword is used to transfer control from the try block to the
catch block.
4. throws: The throws keyword is used for exception handling without try & catch
block. It specifies the exceptions that a method can throw to the caller and does
not handle itself.
5. finally: It is executed after the catch block. We use it to put some common code
(to be executed irrespective of whether an exception has occurred or not ) when
there are multiple catch blocks.
Divyavani, Assistant Professor 8
This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed after try block ends
}
Divyavani, Assistant Professor 9
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
}
10
class ThrowsExecp {
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}
11
12
throw, throws, and finally keywords in Java
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try blcok. When JVM encounters the throw keyword,
it stops the execution of try block and jump to the corresponding catch block.
 Using throw keyword only object of Throwable class or its sub classes
can be thrown.
Using throw keyword only one exception can be thrown.
The throw keyword must followed by an throwable instance.
Syntax
throw instance;
Here the instace must be throwable instance and it
can be created dynamically using new operator.
13
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division
by zero is not posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "="
+ result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the program");
}
}
14
throws keyword in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
🔔 When a method throws an exception, we must put the calling statement of method
in try-catch block.
import java.util.Scanner;
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException {
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
public static void main(String[] args) {
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the program");
}
}
15
Important Points to Remember about throws Keyword
 throws keyword is required only for checked exceptions and usage of the throws
keyword for unchecked exceptions is meaningless.
 throws keyword is required only to convince the compiler and usage of the throws
keyword does not prevent abnormal termination of the program.
 With the help of the throws keyword, we can provide information to the caller of the
method about the exception.
16
finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
🔔 Only one finally block is allowed for each try block.
🔔 Use of finally block is optional.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if the program exits (either by calling System.exit() or
by causing a fatal error that causes the process to abort).
17
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
18
import java.util.Scanner;
public class FinallyExample {
public static void main(String[] args) {
int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division
by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "="
+ result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
finally {
System.out.println("The finally block execut
always");
}
System.out.println("End of the program");
}
}
19
When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the program
terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or
not
finally {
System.out.println("finally block is always
executed");
}
System.out.println("rest of the code...");
}
}
20
Sr. no. Basis of Differences throw throws
1. Definition Java throw keyword is
used throw an exception
explicitly in the code,
inside the function or the
block of code.
Java throws keyword is
used in the method
signature to declare an
exception which might be
thrown by the function
while the execution of the
code.
2. Type of exception Using
throw keyword, we can
only propagate unchecked
exception i.e., the checked
exception cannot be
propagated using throw
only.
Using throws keyword, we
can declare both checked
and unchecked
exceptions. However, the
throws keyword can be
used to propagate
checked exceptions only.
3. Syntax The throw keyword is
followed by an instance of
Exception to be thrown.
The throws keyword is
followed by class names of
Exceptions to be thrown.
4. Declaration throw is used within the
method.
throws is used with the
method signature.
5. Internal implementation We are allowed to throw We can declare multiple
21
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("nNumber is negative, cannot calculate
square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
22
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}
23
Exception Hierarchy
All exception and error types are subclasses of class
Throwable, which is the base class of the hierarchy.
One branch is headed by Exception. This class is used
for exceptional conditions that user programs should
catch. NullPointerException is an example of such an
exception.
Another branch, Error is used by the Java run-time
system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError
is an example of such an error.
24
Types of Exceptions
25
Exceptions can be categorized in two ways:
1. Built-in Exceptions
a) Checked Exception
b) Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.
The following are a few built-in classes used to handle checked exceptions in java.
 IOException
 FileNotFoundException
 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
26
import java.io.*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:UsersUserDesktopTodaySample.txt");
try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}
}
}
27
Unchecked Exceptions:
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it, the program would not give a
compilation error.
The following are a few built-in classes used to handle unchecked exceptions in
java.
 ArithmeticException
 NullPointerException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
28
public class UncheckedException {
public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
System.out.println(list[6]); //ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
29
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations. Below is the list of important built-in exceptions in
Java.
 ArithmeticException: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
 ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed
with an illegal index. The index is either negative or greater than or equal to the size of the
array.
 ClassNotFoundException: This Exception is raised when we try to access a class whose
definition is not found
 FileNotFoundException: This Exception is raised when a file is not accessible or does not
open.
 IOException: It is thrown when an input-output operation failed or interrupted
30
 InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
 NoSuchFieldException: It is thrown when a class does not contain the field (or variable)
specified
 NoSuchMethodException: It is thrown when accessing a method that is not found.
 NullPointerException: This exception is raised when referring to the members of a null
object. Null represents nothing
 NumberFormatException: This exception is raised when a method could not convert a
string into a numeric format.
 RuntimeException: This represents an exception that occurs during runtime.
 StringIndexOutOfBoundsException: It is thrown by String class methods to indicate
that an index is either negative or greater than the size of the string
 IllegalArgumentException : This exception will throw the error or error statement when
the method receives an argument which is not accurately fit to the given relation or
condition. It comes under the unchecked exception.
 IllegalStateException : This exception will throw an error or error message when the
method is not accessed for the particular operation in the application. It comes under the
unchecked exception.
31
A. Arithmetic exception
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
32
B. NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
33
C. StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 24th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("StringIndexOutOfBoundsException");
}
}
}
34
FileNotFound Exception
//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[]) {
try {
// Following file does not exist
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
} }
35
NumberFormat Exception
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
36
ArrayIndexOutOfBounds Exception
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
37
NoSuchMethod Exception
// Java program to demonstrate NoSuchElementException
public class NoSuchElementException_Demo {
public static void main(String[] args)
{
Set exampleleSet = new HashSet();
Hashtable exampleTable = new Hashtable();
exampleleSet.iterator().next();
//accessing Set
exampleTable.elements().nextElement();
//accessing Hashtable
// This throws a NoSuchElementException as there are
// no elements in Set and HashTable and we are
// trying to access elements
}
}
38
IllegalArgumentException: This program, checks whether the person is eligible for voting or not. If the age is
greater than or equal to 18 then it will not throw any error. If the age is less than 18 then it will throw an error
with the error statement.
import java.io.*;
class ABC {
public static void print(int a)
{
if(a>=18){
System.out.println("Eligible for Voting");
}
else{
throw new IllegalArgumentException("Not Eligible for Voting");
}
}
public static void main(String[] args) {
ABC.print(14);
}
}
39
IllegalStateException: This program, displays the addition of numbers only for Positive integers. If both the
numbers are positive then only it will call the print method to print the result otherwise it will throw the
IllegalStateException with an error statement. Here, the method is not accessible for non-positive integers.
import java.io.*;
class GFG {
public static void print(int a,int b)
{
System.out.println("Addition of Positive Integers :"+(a+b));
}
public static void main(String[] args) {
int n1=7;
int n2=-3;
if(n1>=0 && n2>=0)
{
GFG.print(n1,n2);
}
else
{
throw new IllegalStateException("Either one or two numbers are not Positive Integer");
}
40
ClassNotFound Exception :
// Java program to demonstrate ClassNotFoundException
public class ClassNotFoundException_Demo
{
public static void main(String[] args) {
try{
Class.forName("Class1"); // Class1 is not defined
}
catch(ClassNotFoundException e){
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}
41
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
 Provision to Complete Program Execution
 Easy Identification of Program Code and Error-Handling Code
 Propagation of Errors
 Meaningful Error Reporting
 Identifying Error Types
42
import java.io.*;
class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
}
43
The user should create an exception class as a subclass of the Exception class. Since all the
exceptions are subclasses of the Exception class, the user should also make his class a
subclass of it.
This is done as:
class MyException extends Exception
We can write a default constructor in his own exception class.
MyException(){}
We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call the superclass(Exception) constructor
from this and send the string there.
MyException(String str)
{
super(str);
}
44
To raise an exception of a user-defined type, we need to create an object to his exception
class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
The following program illustrates how to create your own exception class MyException.
Details of account numbers, customer names, and balance amounts are taken in the form of three
arrays.
In main() method, the details are displayed using a for-loop. At this time, a check is done if in any
account the balance amount is less than the minimum balance amount to be apt in the account.
If it is so, then MyException is raised and a message is displayed “Balance amount is less”.
45
/ This program throws an exception whenever balance
// amount is below Rs 1000
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};
private static String name[] =
{"Nish", "Shubh", "Sush", "Abhi", "Akash"};
private static double bal[] =
{10000.00, 12000.00, 5600.0, 999.00, 1100.55};
// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
46
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "t" + "CUSTOMER" +
"t" + "BALANCE");
// display the actual account information
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "t" + name[i] +
"t" + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
}
//end of try
catch (MyException e) {
e.printStackTrace();}}}
Runtime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
47
Java Multiple Catch Block
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
48
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
}
49
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
}
50
In this example, try block contains two exceptions. But at a time only one exception occurs and
its corresponding catch block is executed.
public class MultipleCatchBlock3 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
}
51
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception class Exception will
invoked.
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
52
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e. from
most specific to most general).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common
task completed");}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
53
Before Java 7, we had to catch only one exception type in each catch block. So, whenever we needed
to handle more than one specific exception but take some action for all exceptions, we had to have
more than one catch block containing the same code.
In the following code, we have to handle two different exceptions but take the same action for both.
So we needed to have two different catch blocks as of Java 6.0.
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format
Exception " + ex);
}
}
}
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
54
Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by
separating each with | (pipe symbol) in the catch block.
Catching multiple exceptions in a single catch block reduces code duplication and increases
efficiency. The bytecode generated while compiling this program will be smaller than the
program having multiple catch blocks as there is no code redundancy.
Note: If a catch block handles multiple exceptions,
the catch parameter is implicitly final. This means
we cannot assign any values to catch parameters.
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}
55
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (NumberFormatException | ArithmeticException ex)
{
System.out.println("Exception encountered " + ex);
}
}
}
56
Important Points:
1. If all the exceptions belong to the same class hierarchy, we should be catching the base
exception type. However, to catch each exception, it needs to be done separately in their catch
blocks.
2. Single catch block can handle more than one type of exception. However, the base (or
ancestor) class and subclass (or descendant) exceptions can not be caught in one statement. For
Example
// Not Valid as Exception is an ancestor of
// NumberFormatException
catch(NumberFormatException | Exception ex)
3. All the exceptions must be separated by vertical bar pipe |.
57
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed
onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
58
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
} }
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
Syntax
59
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
60
catch(Exception e)
{
System.out.println("handled the exception (outer
catch)");
}
System.out.println("normal flow..");
}
}
When any try block does not have a catch block for a particular excetion, then the catch block
of the outer (parent) try block are checked for that exception, and if it matches, the catch
block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the
Java runtime system will handle the exception. Then it displays the system generated
message for that exception.
p
61
Let's consider the following example. Here the try block within nested try block (inner try
block 2) do not handle the exception. The control is then transferred to its parent try
block (inner try block 1). If it does not handle the exception, then the control is
transferred to the main try block (outer try block) where the appropriate catch block
handles the exception. It is termed as nesting.
62
public class NestedTryBlock2 {
public static void main(String args[])
{
// outer (main) try block
try {
//inner try block 1
try {
// inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out of its bounds
System.out.println(arr[10]);
}
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
} }
catch (ArithmeticException e) {
System.out.println("Arithmetic exceptio
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsExcepti
catch (ArrayIndexOutOfBoundsException e4
System.out.print(e4);
System.out.println(" outer (main) try bloc
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-
block");
}
}
}
63
Exception Models in Java
Java programming language has two models of exception handling. The exception models that java suports are as
follows.
 Termination Model
 Resumptive Model
Termination Model:
In the termination model, when a method encounters an exception, further processing in that method is terminated
and control is transferred to the nearest catch block that can handle the type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get back to where the
exception occurred.
Resumptive Model:
The alternative of termination model is resumptive model. In resumptive model, the exception handler is expected to
do something to stable the situation, and then the faulting method is retried. In resumptive model we hope to
continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may also place the try block
in a while loop that keeps re-entering the try block util the result is satisfactory.
64
Uncaught Exceptions in Java
 In java, assume that, if we do not handle the exceptions in a program. In this case, when
an exception occurs in a particular function, then Java prints a exception message with
the help of uncaught exception handler.
 The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
 Java programming language has a very strong exception handling mechanism. It allow us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
 When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
 The Division by zero exception is one of the example for uncaught exceptions. Look at the
following code.
65
import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
} In the above example code, we are not used try and catch blocks, but
when the value of b is zero the division by zero exception occurs and it
caught by the default exception handler.
66
 Write a Java program to create a method that takes an integer as a parameter and throws
an exception if the number is odd.
 Write a Java program that reads a list of integers from the user and throws an exception if
any numbers are duplicates.
 Write a Java program to create a method that takes a string as input and throws an
exception if the string does not contain vowels.
https://www.w3resource.com/java-exercises/exception/index.php

Exception Handling inJava Programming.pptx

  • 1.
  • 2.
    Divyavani, Assistant Professor2 The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Exception Handling in Java What is Exception in Java? Dictionary Meaning: Exception is an abnormal condition. Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
  • 3.
    Divyavani, Assistant Professor3 Major reasons why an exception Occurs:  Invalid user input  Device failure  Loss of network connection  Physical limitations (out of disk memory)  Code errors  Opening an unavailable file Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors. differences between Error and Exception Error: An Error indicates a serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch.
  • 4.
    Divyavani, Assistant Professor4 Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.  That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.  Exceptions can be generated by the Java run-time system, or they can be manually generated by your code.
  • 5.
    Divyavani, Assistant Professor5  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  Program statements that you want to monitor for exceptions are contained within a try block.  If an exception occurs within the try block, it is thrown.  Your code can catch this exception (using catch) and handle it in some rational manner.  System-generated exceptions are automatically thrown by the Java run-time system.  To manually throw an exception, use the keyword throw.  Any exception that is thrown out of a method must be specified as such by a throws clause.  Any code that absolutely must be executed after a try block completes is put in a finally block.
  • 6.
    Divyavani, Assistant Professor6 1. try: The try block contains a set of statements where an exception can occur. try { // statement(s) that might cause exception } 2. catch: The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block. catch { // statement(s) that handle an exception // examples, closing a connection, closing // file, exiting the process after writing // details to a log file. }
  • 7.
    Divyavani, Assistant Professor7 3. throw: The throw keyword is used to transfer control from the try block to the catch block. 4. throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. 5. finally: It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there are multiple catch blocks.
  • 8.
    Divyavani, Assistant Professor8 This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } finally { // block of code to be executed after try block ends }
  • 9.
    Divyavani, Assistant Professor9 class Division { public static void main(String[] args) { int a = 10, b = 5, c = 5, result; try { result = a / (b - c); System.out.println("result" + result); } catch (ArithmeticException e) { System.out.println("Exception caught:Division by zero"); } finally { System.out.println("I am in final block"); } } }
  • 10.
    10 class ThrowsExecp { staticvoid fun() throws IllegalAccessException { System.out.println("Inside fun(). "); throw new IllegalAccessException("demo"); } // This is a caller function public static void main(String args[]) { try { fun(); } catch (IllegalAccessException e) { System.out.println("caught in main."); } } }
  • 11.
  • 12.
    12 throw, throws, andfinally keywords in Java throw keyword in Java The throw keyword is used to throw an exception instance explicitly from a try block to corresponding catch block. That means it is used to transfer the control from try block to corresponding catch block. The throw keyword must be used inside the try blcok. When JVM encounters the throw keyword, it stops the execution of try block and jump to the corresponding catch block.  Using throw keyword only object of Throwable class or its sub classes can be thrown. Using throw keyword only one exception can be thrown. The throw keyword must followed by an throwable instance. Syntax throw instance; Here the instace must be throwable instance and it can be created dynamically using new operator.
  • 13.
    13 import java.util.Scanner; public classSample { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num1, num2, result; System.out.print("Enter any two numbers: "); num1 = input.nextInt(); num2 = input.nextInt(); try { if(num2 == 0) throw new ArithmeticException("Division by zero is not posible"); result = num1 / num2; System.out.println(num1 + "/" + num2 + "=" + result); } catch(ArithmeticException ae) { System.out.println("Problem info: " + ae.getMessage()); } System.out.println("End of the program"); } }
  • 14.
    14 throws keyword inJava The throws keyword specifies the exceptions that a method can throw to the default handler and does not handle itself. That means when we need a method to throw an exception automatically, we use throws keyword followed by method declaration 🔔 When a method throws an exception, we must put the calling statement of method in try-catch block. import java.util.Scanner; public class ThrowsExample { int num1, num2, result; Scanner input = new Scanner(System.in); void division() throws ArithmeticException { System.out.print("Enter any two numbers: "); num1 = input.nextInt(); num2 = input.nextInt(); result = num1 / num2; System.out.println(num1 + "/" + num2 + "=" + result); } public static void main(String[] args) { try { new ThrowsExample().division(); } catch(ArithmeticException ae) { System.out.println("Problem info: " + ae.getMessage()); } System.out.println("End of the program"); } }
  • 15.
    15 Important Points toRemember about throws Keyword  throws keyword is required only for checked exceptions and usage of the throws keyword for unchecked exceptions is meaningless.  throws keyword is required only to convince the compiler and usage of the throws keyword does not prevent abnormal termination of the program.  With the help of the throws keyword, we can provide information to the caller of the method about the exception.
  • 16.
    16 finally keyword inJava The finally keyword used to define a block that must be executed irrespective of exception occurence. The basic purpose of finally keyword is to cleanup resources allocated by try block, such as closing file, closing database connection, etc. 🔔 Only one finally block is allowed for each try block. 🔔 Use of finally block is optional. Rule: For each try block there can be zero or more catch blocks, but only one finally block. Note: The finally block will not be executed if the program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).
  • 17.
    17 Syntax try { // Protectedcode } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. }
  • 18.
    18 import java.util.Scanner; public classFinallyExample { public static void main(String[] args) { int num1, num2, result; Scanner input = new Scanner(System.in); System.out.print("Enter any two numbers: "); num1 = input.nextInt(); num2 = input.nextInt(); try { if(num2 == 0) throw new ArithmeticException("Division by zero"); result = num1 / num2; System.out.println(num1 + "/" + num2 + "=" + result); } catch(ArithmeticException ae) { System.out.println("Problem info: " + ae.getMessage()); } finally { System.out.println("The finally block execut always"); } System.out.println("End of the program"); } }
  • 19.
    19 When an exceptionoccurr but not handled by the catch block Let's see the the fillowing example. Here, the code throws an exception however the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally. public class TestFinallyBlock1{ public static void main(String args[]){ try { System.out.println("Inside the try block"); //below code throws divide by zero exception int data=25/0; System.out.println(data); } catch(NullPointerException e){ System.out.println(e); } //executes regardless of exception occured or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } }
  • 20.
    20 Sr. no. Basisof Differences throw throws 1. Definition Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code. Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code. 2. Type of exception Using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only. Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only. 3. Syntax The throw keyword is followed by an instance of Exception to be thrown. The throws keyword is followed by class names of Exceptions to be thrown. 4. Declaration throw is used within the method. throws is used with the method signature. 5. Internal implementation We are allowed to throw We can declare multiple
  • 21.
    21 public class TestThrow{ //defining a method public static void checkNum(int num) { if (num < 1) { throw new ArithmeticException("nNumber is negative, cannot calculate square"); } else { System.out.println("Square of " + num + " is " + (num*num)); } } //main method public static void main(String[] args) { TestThrow obj = new TestThrow(); obj.checkNum(-3); System.out.println("Rest of the code.."); } }
  • 22.
    22 public class TestThrows{ //defining a method public static int divideNum(int m, int n) throws ArithmeticException { int div = m / n; return div; } //main method public static void main(String[] args) { TestThrows obj = new TestThrows(); try { System.out.println(divideNum(45, 0)); } catch (ArithmeticException e){ System.out.println("nNumber cannot be divided by 0"); } System.out.println("Rest of the code.."); } }
  • 23.
    23 Exception Hierarchy All exceptionand error types are subclasses of class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
  • 24.
  • 25.
    25 Exceptions can becategorized in two ways: 1. Built-in Exceptions a) Checked Exception b) Unchecked Exception 2. User-Defined Exceptions 1. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. The following are a few built-in classes used to handle checked exceptions in java.  IOException  FileNotFoundException  ClassNotFoundException  SQLException  DataAccessException  InstantiationException
  • 26.
    26 import java.io.*; public classCheckedExceptions { public static void main(String[] args) { File f_ref = new File("C:UsersUserDesktopTodaySample.txt"); try { FileReader fr = new FileReader(f_ref); }catch(Exception e) { System.out.println(e); } } }
  • 27.
    27 Unchecked Exceptions: The uncheckedexceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error. The following are a few built-in classes used to handle unchecked exceptions in java.  ArithmeticException  NullPointerException  NumberFormatException  ArrayIndexOutOfBoundsException  StringIndexOutOfBoundsException
  • 28.
    28 public class UncheckedException{ public static void main(String[] args) { int list[] = {10, 20, 30, 40, 50}; System.out.println(list[6]); //ArrayIndexOutOfBoundsException String msg=null; System.out.println(msg.length()); //NullPointerException String name="abc"; int i=Integer.parseInt(name); //NumberFormatException } }
  • 29.
    29 Built-in Exceptions: Built-in exceptionsare the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.  ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic operation.  ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.  ClassNotFoundException: This Exception is raised when we try to access a class whose definition is not found  FileNotFoundException: This Exception is raised when a file is not accessible or does not open.  IOException: It is thrown when an input-output operation failed or interrupted
  • 30.
    30  InterruptedException: Itis thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.  NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified  NoSuchMethodException: It is thrown when accessing a method that is not found.  NullPointerException: This exception is raised when referring to the members of a null object. Null represents nothing  NumberFormatException: This exception is raised when a method could not convert a string into a numeric format.  RuntimeException: This represents an exception that occurs during runtime.  StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string  IllegalArgumentException : This exception will throw the error or error statement when the method receives an argument which is not accurately fit to the given relation or condition. It comes under the unchecked exception.  IllegalStateException : This exception will throw an error or error message when the method is not accessed for the particular operation in the application. It comes under the unchecked exception.
  • 31.
    31 A. Arithmetic exception classArithmeticException_Demo { public static void main(String args[]) { try { int a = 30, b = 0; int c = a/b; // cannot divide by zero System.out.println ("Result = " + c); } catch(ArithmeticException e) { System.out.println ("Can't divide a number by 0"); } } }
  • 32.
    32 B. NullPointer Exception //Javaprogram to demonstrate NullPointerException class NullPointer_Demo { public static void main(String args[]) { try { String a = null; //null value System.out.println(a.charAt(0)); } catch(NullPointerException e) { System.out.println("NullPointerException.."); } } }
  • 33.
    33 C. StringIndexOutOfBound Exception //Java program to demonstrate StringIndexOutOfBoundsException class StringIndexOutOfBound_Demo { public static void main(String args[]) { try { String a = "This is like chipping "; // length is 22 char c = a.charAt(24); // accessing 24th element System.out.println(c); } catch(StringIndexOutOfBoundsException e) { System.out.println("StringIndexOutOfBoundsException"); } } }
  • 34.
    34 FileNotFound Exception //Java programto demonstrate FileNotFoundException import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; class File_notFound_Demo { public static void main(String args[]) { try { // Following file does not exist File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } catch (FileNotFoundException e) { System.out.println("File does not exist"); } } }
  • 35.
    35 NumberFormat Exception // Javaprogram to demonstrate NumberFormatException class NumberFormat_Demo { public static void main(String args[]) { try { // "akki" is not a number int num = Integer.parseInt ("akki") ; System.out.println(num); } catch(NumberFormatException e) { System.out.println("Number format exception"); } } }
  • 36.
    36 ArrayIndexOutOfBounds Exception // Javaprogram to demonstrate ArrayIndexOutOfBoundException class ArrayIndexOutOfBound_Demo { public static void main(String args[]) { try{ int a[] = new int[5]; a[6] = 9; // accessing 7th element in an array of // size 5 } catch(ArrayIndexOutOfBoundsException e){ System.out.println ("Array Index is Out Of Bounds"); } } }
  • 37.
    37 NoSuchMethod Exception // Javaprogram to demonstrate NoSuchElementException public class NoSuchElementException_Demo { public static void main(String[] args) { Set exampleleSet = new HashSet(); Hashtable exampleTable = new Hashtable(); exampleleSet.iterator().next(); //accessing Set exampleTable.elements().nextElement(); //accessing Hashtable // This throws a NoSuchElementException as there are // no elements in Set and HashTable and we are // trying to access elements } }
  • 38.
    38 IllegalArgumentException: This program,checks whether the person is eligible for voting or not. If the age is greater than or equal to 18 then it will not throw any error. If the age is less than 18 then it will throw an error with the error statement. import java.io.*; class ABC { public static void print(int a) { if(a>=18){ System.out.println("Eligible for Voting"); } else{ throw new IllegalArgumentException("Not Eligible for Voting"); } } public static void main(String[] args) { ABC.print(14); } }
  • 39.
    39 IllegalStateException: This program,displays the addition of numbers only for Positive integers. If both the numbers are positive then only it will call the print method to print the result otherwise it will throw the IllegalStateException with an error statement. Here, the method is not accessible for non-positive integers. import java.io.*; class GFG { public static void print(int a,int b) { System.out.println("Addition of Positive Integers :"+(a+b)); } public static void main(String[] args) { int n1=7; int n2=-3; if(n1>=0 && n2>=0) { GFG.print(n1,n2); } else { throw new IllegalStateException("Either one or two numbers are not Positive Integer"); }
  • 40.
    40 ClassNotFound Exception : //Java program to demonstrate ClassNotFoundException public class ClassNotFoundException_Demo { public static void main(String[] args) { try{ Class.forName("Class1"); // Class1 is not defined } catch(ClassNotFoundException e){ System.out.println(e); System.out.println("Class Not Found..."); } } }
  • 41.
    41 User-Defined Exceptions: Sometimes, thebuilt-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’. The advantages of Exception Handling in Java are as follows:  Provision to Complete Program Execution  Easy Identification of Program Code and Error-Handling Code  Propagation of Errors  Meaningful Error Reporting  Identifying Error Types
  • 42.
    42 import java.io.*; class GFG{ public static void main (String[] args) { int a=5; int b=0; try{ System.out.println(a/b); } catch(ArithmeticException e) { e.printStackTrace(); } } }
  • 43.
    43 The user shouldcreate an exception class as a subclass of the Exception class. Since all the exceptions are subclasses of the Exception class, the user should also make his class a subclass of it. This is done as: class MyException extends Exception We can write a default constructor in his own exception class. MyException(){} We can also create a parameterized constructor with a string as a parameter. We can use this to store exception details. We can call the superclass(Exception) constructor from this and send the string there. MyException(String str) { super(str); }
  • 44.
    44 To raise anexception of a user-defined type, we need to create an object to his exception class and throw it using the throw clause, as: MyException me = new MyException(“Exception details”); throw me; The following program illustrates how to create your own exception class MyException. Details of account numbers, customer names, and balance amounts are taken in the form of three arrays. In main() method, the details are displayed using a for-loop. At this time, a check is done if in any account the balance amount is less than the minimum balance amount to be apt in the account. If it is so, then MyException is raised and a message is displayed “Balance amount is less”.
  • 45.
    45 / This programthrows an exception whenever balance // amount is below Rs 1000 class MyException extends Exception { //store account information private static int accno[] = {1001, 1002, 1003, 1004}; private static String name[] = {"Nish", "Shubh", "Sush", "Abhi", "Akash"}; private static double bal[] = {10000.00, 12000.00, 5600.0, 999.00, 1100.55}; // default constructor MyException() { } // parameterized constructor MyException(String str) { super(str); }
  • 46.
    46 public static voidmain(String[] args) { try { // display the heading for the table System.out.println("ACCNO" + "t" + "CUSTOMER" + "t" + "BALANCE"); // display the actual account information for (int i = 0; i < 5 ; i++) { System.out.println(accno[i] + "t" + name[i] + "t" + bal[i]); // display own exception if balance < 1000 if (bal[i] < 1000) { MyException me = new MyException("Balance is less than 1000"); throw me; } } } //end of try catch (MyException e) { e.printStackTrace();}}} Runtime Error MyException: Balance is less than 1000 at MyException.main(fileProperty.java:36)
  • 47.
    47 Java Multiple CatchBlock A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.  At a time only one exception occurs and at a time only one catch block is executed.  All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 48.
    48 public class MultipleCatchBlock1{ public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }
  • 49.
    49 public class MultipleCatchBlock2{ public static void main(String[] args) { try{ int a[]=new int[5]; System.out.println(a[10]); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }
  • 50.
    50 In this example,try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed. public class MultipleCatchBlock3 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; System.out.println(a[10]); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }
  • 51.
    51 In this example,we generate NullPointerException, but didn't provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked. public class MultipleCatchBlock4 { public static void main(String[] args) { try{ String s=null; System.out.println(s.length()); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); }
  • 52.
    52 Let's see anexample, to handle the exception without maintaining the order of exceptions (i.e. from most specific to most general). class MultipleCatchBlock5{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){System.out.println("common task completed");} catch(ArithmeticException e) {System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e) {System.out.println("task 2 completed");} System.out.println("rest of the code..."); } }
  • 53.
    53 Before Java 7,we had to catch only one exception type in each catch block. So, whenever we needed to handle more than one specific exception but take some action for all exceptions, we had to have more than one catch block containing the same code. In the following code, we have to handle two different exceptions but take the same action for both. So we needed to have two different catch blocks as of Java 6.0. catch (ArithmeticException ex) { System.out.println("Arithmetic " + ex); } catch (NumberFormatException ex) { System.out.println("Number Format Exception " + ex); } } } import java.util.Scanner; public class Test { public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); }
  • 54.
    54 Starting from Java7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency. The bytecode generated while compiling this program will be smaller than the program having multiple catch blocks as there is no code redundancy. Note: If a catch block handles multiple exceptions, the catch parameter is implicitly final. This means we cannot assign any values to catch parameters. Syntax: try { // code } catch (ExceptionType1 | Exceptiontype2 ex){ // catch block }
  • 55.
    55 import java.util.Scanner; public classTest { public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); } catch (NumberFormatException | ArithmeticException ex) { System.out.println("Exception encountered " + ex); } } }
  • 56.
    56 Important Points: 1. Ifall the exceptions belong to the same class hierarchy, we should be catching the base exception type. However, to catch each exception, it needs to be done separately in their catch blocks. 2. Single catch block can handle more than one type of exception. However, the base (or ancestor) class and subclass (or descendant) exceptions can not be caught in one statement. For Example // Not Valid as Exception is an ancestor of // NumberFormatException catch(NumberFormatException | Exception ex) 3. All the exceptions must be separated by vertical bar pipe |.
  • 57.
    57 Java Nested tryblock In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack. For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero). Why use nested try block? Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
  • 58.
    58 try { statement 1; statement 2; //trycatch block within another try block try { statement 3; statement 4; //try catch block within nested try block try { statement 5; statement 6; } catch(Exception e2) { //exception message } } catch(Exception e1) { //exception message } } //catch block of parent (outer) try block catch(Exception e3) { //exception message } Syntax
  • 59.
    59 public class NestedTryBlock{ publicstatic void main(String args[]){ //outer try block try{ //inner try block 1 try{ System.out.println("going to divide by 0"); int b =39/0; } //catch block of inner try block 1 catch(ArithmeticException e) { System.out.println(e); } try{ int a[]=new int[5]; //assigning the value out of array bounds a[5]=4; } //catch block of inner try block 2 catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement"); }
  • 60.
    60 catch(Exception e) { System.out.println("handled theexception (outer catch)"); } System.out.println("normal flow.."); } } When any try block does not have a catch block for a particular excetion, then the catch block of the outer (parent) try block are checked for that exception, and if it matches, the catch block of outer try block is executed. If none of the catch block specified in the code is unable to handle the exception, then the Java runtime system will handle the exception. Then it displays the system generated message for that exception. p
  • 61.
    61 Let's consider thefollowing example. Here the try block within nested try block (inner try block 2) do not handle the exception. The control is then transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. It is termed as nesting.
  • 62.
    62 public class NestedTryBlock2{ public static void main(String args[]) { // outer (main) try block try { //inner try block 1 try { // inner try block 2 try { int arr[] = { 1, 2, 3, 4 }; //printing the array element out of its bounds System.out.println(arr[10]); } // to handles ArithmeticException catch (ArithmeticException e) { System.out.println("Arithmetic exception"); System.out.println(" inner try block 2"); } } catch (ArithmeticException e) { System.out.println("Arithmetic exceptio System.out.println("inner try block 1"); } } // to handle ArrayIndexOutOfBoundsExcepti catch (ArrayIndexOutOfBoundsException e4 System.out.print(e4); System.out.println(" outer (main) try bloc } catch (Exception e5) { System.out.print("Exception"); System.out.println(" handled in main try- block"); } } }
  • 63.
    63 Exception Models inJava Java programming language has two models of exception handling. The exception models that java suports are as follows.  Termination Model  Resumptive Model Termination Model: In the termination model, when a method encounters an exception, further processing in that method is terminated and control is transferred to the nearest catch block that can handle the type of exception encountered. In other words we can say that in termination model the error is so critical there is no way to get back to where the exception occurred. Resumptive Model: The alternative of termination model is resumptive model. In resumptive model, the exception handler is expected to do something to stable the situation, and then the faulting method is retried. In resumptive model we hope to continue the execution after the exception is handled. In resumptive model we may use a method call that want resumption like behavior. We may also place the try block in a while loop that keeps re-entering the try block util the result is satisfactory.
  • 64.
    64 Uncaught Exceptions inJava  In java, assume that, if we do not handle the exceptions in a program. In this case, when an exception occurs in a particular function, then Java prints a exception message with the help of uncaught exception handler.  The uncaught exceptions are the exceptions that are not caught by the compiler but automatically caught and handled by the Java built-in exception handler.  Java programming language has a very strong exception handling mechanism. It allow us to handle the exception use the keywords like try, catch, finally, throw, and throws.  When an uncaught exception occurs, the JVM calls a special private method known dispatchUncaughtException( ), on the Thread class in which the exception occurs and terminates the thread.  The Division by zero exception is one of the example for uncaught exceptions. Look at the following code.
  • 65.
    65 import java.util.Scanner; public classUncaughtExceptionExample { public static void main(String[] args) { Scanner read = new Scanner(System.in); System.out.println("Enter the a and b values: "); int a = read.nextInt(); int b = read.nextInt(); int c = a / b; System.out.println(a + "/" + b +" = " + c); } } In the above example code, we are not used try and catch blocks, but when the value of b is zero the division by zero exception occurs and it caught by the default exception handler.
  • 66.
    66  Write aJava program to create a method that takes an integer as a parameter and throws an exception if the number is odd.  Write a Java program that reads a list of integers from the user and throws an exception if any numbers are duplicates.  Write a Java program to create a method that takes a string as input and throws an exception if the string does not contain vowels. https://www.w3resource.com/java-exercises/exception/index.php