0% found this document useful (0 votes)
33 views22 pages

Exception Handling II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views22 pages

Exception Handling II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

JAVA Programming

Course Instructor: Dr. Suvojit Dhara


School of Computer Science
UPES Dehradun
TOPICs to be discussed

 Exception handling in Java

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

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

 The try and catch keywords come in pairs.

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

System.out.println("Enter the elements : "); (1) Enter the elements :


for(int i = 0; i < 5; i++) 12345
arr[i] = sc.nextInt(); Enter a limit :
System.out.println("Enter a limit : "); 3
int k = sc.nextInt(); Sum of the 3 elements is : 6
System.out.print("Sum of the "+k+" elements is : ");
int sum = 0;
for(int i = 0; i < k; i++) (2) Enter the elements :
sum += arr[i];
12345
System.out.print(sum);
}catch(ArrayIndexOutOfBoundsException e) { Enter a limit :
System.out.println("Oh, no! You went too ahead, 6
limit
Sum of the 6 elements is :
yourself to index four...");
} Oh, no! You went too ahead,
} limit yourself to index four...
}
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];

System.out.println("Enter the elements : "); (3) Enter the elements :


for(int i = 0; i < 5; i++) one two three four five
arr[i] = sc.nextInt();
Exception in thread "main"
System.out.println("Enter a limit : "); java.util.InputMismatchException
int k = sc.nextInt(); ...
System.out.print("Sum of the "+k+" elements is : ");
int sum = 0;
...
for(int i = 0; i < k; i++)
sum += arr[i];
System.out.print(sum);
Note:
}catch(ArrayIndexOutOfBoundsException e) { Our program execution did not
System.out.println("Oh, no! You went too ahead, reach to the catch mechanism
limit
yourself to index four..."); and the exception thrown in it,
} rather it throws another
}
} exception by default.
try with multiple catch (Example)
import java.util.*;
class Multi_TryCatch {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
int arr[] = new int[5]; System.out.println("Enter the elements : ");
for(int i = 0; i < 5; i++) { arr[i] = sc.nextInt(); }

System.out.println("Enter a limit : "); int k = sc.nextInt();


System.out.print("Sum of the "+k+" elements is : ");
int sum = 0; for(int i = 0; i < k; i++) { sum += arr[i]; }
System.out.print(sum);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Oh, no! You went too ahead, limit yourself to index four...");
}catch(InputMismatchException e) {
System.out.println("Array elements are all integers, so please input an integer");
}
}
}

Output: Enter the elements :


one two three four five
Array elements are all integers, so please input an integer
Order of execution of catch blocks
 The order of exception handling in the catch block must be from the most specific
exception.
class MultipleCatch {
public static void main(String[] args) {
try {
int result = 10 / 0; //Division by zero
System.out.println(result);
int[] num = {1, 2, 3, 4, 5};
System.out.println(num[5]); //Accessing an array with an out-of-bounds index
} catch (ArithmeticException e) {
System.out.println("Exception occurred: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occurred: " + e.getMessage());
} catch (Exception e) {
System.out.println("Exception occurred: " + e.toString());
}
}
}

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

• Exception handling in Java


• Simple try-catch block
• try with multiple catch (order of execution)
• Single try for catching multiple errors
• finally keyword
• Use of throw and throws keyword

You might also like