Exception Handling II
Exception Handling II
try-catch block
finally block
Use of throw, throws keywords
Let’s START …!!!
Exception handling in Java
Exception handling in Java is a mechanism that allows you to gracefully handle and recover
from runtime errors or exceptional conditions that may occur during the execution of a
Java program.
It helps prevent the program from crashing and provides a way to handle errors in a
controlled manner.
Java exception handling is managed via five keywords:
try
catch
finally
throw
throws
Exception handling (Contd..)
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 runtime system.
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.
try-catch block
The try statement allows you to define a block of code to be tested for errors while it is
being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Simple try-catch block (Example)
import java.util.Scanner; import java.util.Scanner;
class Simple_TryCatch1 { class Simple_TryCatch1 {
public static void main(String[] args) { public static void main(String[] args) {
try { Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(System.in); int a = sc.nextInt();
int a = sc.nextInt(); int b = sc.nextInt();
int b = sc.nextInt();
try {
System.out.println(a+"/"+b+" = "+a/b); System.out.println(a+"/"+b+" = "+a/b);
}catch(ArithmeticException e) { }catch(ArithmeticException e) {
System.out.println(e); System.out.println("Division by zero
}
} is not allowed");
} }
}
Output: }
Output:
(1) 4 2 4/2 = 2
4 0 Division by zero is not allowed
(2) 4 0 java.lang.ArithmeticException:
/ by zero
Simple try-catch block (Example)
import java.util.Scanner;
class Simple_TryCatch2 {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in); Output:
int arr[] = new int[5];
Output:
Exception occurred: / by zero
Order of execution of catch blocks
class MultipleCatch {
public static void main(String[] args) {
try {
//Division by zero
int result = 10 / 0;
System.out.println(result);
//Accessing an array with an
out-of-bounds index
int[] num = {1, 2, 3, 4, 5};
System.out.println(num[5]);
} catch (Exception e) {
System.out.println("Exception occurred: " + Output:
e.toString()); Error: exception ArithmeticException has already
} catch (ArithmeticException e) { been caught
System.out.println("Exception occurred: " +
e.getMessage()); } catch (ArithmeticException e) {
^
} catch (ArrayIndexOutOfBoundsException e) {
Error: exception ArrayIndexOutOfBoundsException
System.out.println("Exception occurred: " + has already been caught
e.getMessage());
} } catch (ArrayIndexOutOfBoundsException e) {
}
}
Multiple Errors with single Catch
(Example)
class Single_Catch {
public static void main(String[] args) {
for(int i = 0; i < 4; i++) {
try {
switch(i) { Output:
case 0: int j = 2/i; break;
case 1: int[] a = {}; a[i] = 2; break; In testcase-0 :
case 2: char ch = "java".charAt(i+3); break; / by zero
case 3: int[] b = null; j = b[0]; break;
} In testcase-1 :
}catch(Exception e) {
System.out.println("In testcase-"+i+" : "); Index 1 out of bounds for
System.out.println(e.getMessage()); length 0
}
} In testcase-2 :
}
}
String index out of range: 5
In testcase-3 :
null
finally block
The finally block is used to specify a block of code that will always be executed, regardless
of whether an exception is thrown or not.
Any code that absolutely must be executed after a try block completes is put in a finally
block.
finally can not be used without try.
import java.util.Scanner; Output:
class TryCatchFinally {
public static void main(String[] args) { (1) Enter two numbers : 4 2
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers : "); 4/2 = 2
int a = sc.nextInt(); int b = sc.nextInt();
try {
The second number must be non-zero...
System.out.println(a+"/"+b+" = "+a/b);
}catch(ArithmeticException e) { (2) Enter two numbers : 4 0
e.printStackTrace();
}finally { java.lang.ArithmeticException: / by
System.out.println("The second number must zero
be non-zero..."); at Main.main(Main.java:10)
}
} The second number must be non-zero...
}
Some Queries about finally
How to ensure that finally block does not get executed in case of no exception occurring in
the program?
Answer: Use System.exit(0) to forcefully exit the program (However, this is depreciated)
import java.util.Scanner;
class TryCatchFinally {
public static void main(String[] args) {
Output:
Scanner sc = new Scanner(System.in); (1) Enter two numbers : 4 2
System.out.print("Enter two numbers : ");
int a = sc.nextInt(); int b = sc.nextInt(); 4/2 = 2
try {
System.out.println(a+"/"+b+" = "+a/b);
System.exit(0); //Forceful exit (2) Enter two numbers : 4 0
}catch(ArithmeticException e) {
e.printStackTrace(); java.lang.ArithmeticException: / by
}finally { zero
System.out.println("The second number must
at Main.main(Main.java:10)
be non-zero..."); The second number must be non-zero...
}
}
}
Some Queries about finally
Can we use try without catch or finally? No
class Only_Try { Output:
public static void main(String[] args) {
try { System.out.println(3/0); } Error: 'try' without 'catch', 'finally' or resource
} declarations
}
try { System.out.println(3/0); }
^
Can we use try without catch but only finally? Yes
class TryFinally {
public static void main(String[] args) {
try {
System.out.println(3/0); Output:
}finally {
Division by zero is not allowed
System.out.println("Division by zero
Exception in thread "main"
is not allowed");
}
java.lang.ArithmeticException: / by zero
} at Main.main(Main.java:4)
}
Some Queries about finally
Can we use catch after finally with try? No
class TryFinallyCatch {
public static void main(String[] args) {
try {
System.out.println(3/0);
}finally {
System.out.println("Division by zero
is not allowed");
}catch(Exception e) {
System.out.println(e.toString());
}
} Output:
}
error: 'catch' without 'try'
}catch(Exception e) {
^
Some points to Remember
Note:
For each try block there may be zero or more catch block but only one finally block.
A try block must be followed by either at least one catch block or one finally block, but a
catch block must be preceded by another catch block or a try block.
In case of default catch mechanism, the program will get terminated after displaying the
error message.
If no catch block matches with the Exception type, then finally will get executed (if present)
and then the default catch mechanism will work.
finally block will get executed every time even if no exception raised inside the try block
(unless forcefully exited).
Use of throws keyword
The throws keyword in Java is used to declare an exception.
It gives an information to the programmer that there may occur an exception. So, it is better
for the programmer to provide the exception handling code so that the normal flow of the
program can be maintained.
class Throws_Example {
public static void divide(int a, int b) throws ArithmeticException{
System.out.println(a+"/"+b+" = "+a/b);
}
public static void main(String[] args) {
try {
divide(20, 10); divide(10, 0);
}catch(ArithmeticException e) {
System.out.println("Division by zero is not allowed...");
}
}
}
Output: 20/10 = 2
Division by zero is not allowed...
Use of throw keyword
The throw keyword in Java is used to explicitly throw an exception from a method or any
block of code.
This gives you more control over error handling in your programs.
class Throw_Example {
public static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied –
You must be at least 18 years old."); Output:
} else { Access granted – You are old
System.out.println("Access granted –
You are old enough!"); enough!
} Exception in thread "main"
}
public static void main(String[] args) { java.lang.ArithmeticException:
checkAge(20); Access denied – You must be at least
checkAge(15); 18 years old.
}
} at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
Summary
Today, we learned about