Wednesday 3 January 2024

Unit 4: Exception handling and Multithreading | Java Programming | ICT. Ed 455 | BICTE | Fifth Semester | Bicte blog

 Unit 4: 

Exception handling and Multithreading (3+3)


4.1 The exception hierarchy

4.2 Exception handling fundamentals

4.3 Throwing, re-throwing and catching

4.4 Try, catch, throw, throws, and finally keywords

4.5 Multithreading fundamentals

4.6 Thread class and runnable interface

Practical work

1.       Write a program to implement exception handling in program.

2.       Apply try, catch, throws and finally

3.       Write a program to create threads and multiple threads

Exception Handling in Java

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.

an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

Current Time 0:53

/

Duration 5:19

 

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Example of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario:

  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. statement 10;  

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.

JavaExceptionExample.java

  1. public class JavaExceptionExample{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.       //code that may raise exception  
  5.       int data=100/0;  
  6.    }catch(ArithmeticException e){System.out.println(e);}  
  7.    //rest code of the program   
  8.    System.out.println("rest of the code...");  
  9.   }  
  10. }  

Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

Java try-catch block

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

  1. try{    
  2. //code that may throw an exception    
  3. }catch(Exception_class_Name ref){}    

Syntax of try-finally block

  1. try{    
  2. //code that may throw an exception    
  3. }finally{}    

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block with a single try block.

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:

  • Prints out exception description.
  • Prints the stack trace (Hierarchy of methods where the exception occurred).
  • Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1

TryCatchExample1.java

  1. public class TryCatchExample1 {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         int data=50/0//may throw exception   
  6.           
  7.         System.out.println("rest of the code");  
  8.           
  9.     }  
  10.       
  11. }  

Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in such case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not handled, all the code below the exception won't be executed.

Solution by exception handling

Let's see the solution of the above problem by a java try-catch block.

Example 2

TryCatchExample2.java

  1. public class TryCatchExample2 {  
  2.   
  3.     public static void main(String[] args) {  
  4.         try  
  5.         {  
  6.         int data=50/0//may throw exception   
  7.         }  
  8.             //handling the exception  
  9.         catch(ArithmeticException e)  
  10.         {  
  11.             System.out.println(e);  
  12.         }  
  13.         System.out.println("rest of the code");  
  14.     }  
  15.       
  16. }  

Test it Now

Output:

java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement is printed.

Java finally block

Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).

Why use Java finally block?

  • finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
  • The important statements to be printed can be placed in the finally block.

Usage of Java finally

Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any exception, and the finally block is executed after the try block.

TestFinallyBlock.java

  1. class TestFinallyBlock {    
  2.   public static void main(String args[]){    
  3.   try{    
  4. //below code do not throw any exception  
  5.    int data=25/5;    
  6.    System.out.println(data);    
  7.   }    
  8. //catch won't be executed  
  9.   catch(NullPointerException e){  
  10. System.out.println(e);  
  11. }    
  12. //executed regardless of exception occurred or not  
  13.  finally {  
  14. System.out.println("finally block is always executed");  
  15. }    
  16.     
  17. System.out.println("rest of phe code...");    
  18.   }    
  19. }    

Output:

Case 2: 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.

TestFinallyBlock1.java

  1. public class TestFinallyBlock1{    
  2.       public static void main(String args[]){   
  3.   
  4.       try {    
  5.   
  6.         System.out.println("Inside the try block");  
  7.           
  8.         //below code throws divide by zero exception  
  9.        int data=25/0;    
  10.        System.out.println(data);    
  11.       }    
  12.       //cannot handle Arithmetic type exception  
  13.       //can only accept Null Pointer type exception  
  14.       catch(NullPointerException e){  
  15.         System.out.println(e);  
  16.       }   
  17.   
  18.       //executes regardless of exception occured or not   
  19.       finally {  
  20.         System.out.println("finally block is always executed");  
  21.       }    
  22.   
  23.       System.out.println("rest of the code...");    
  24.       }    
  25.     }    

Output:

Case 3: When an exception occurs and is handled by the catch block

Example:

Let's see the following example where the Java code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.

TestFinallyBlock2.java

  1. public class TestFinallyBlock2{    
  2.       public static void main(String args[]){   
  3.   
  4.       try {    
  5.   
  6.         System.out.println("Inside try block");  
  7.   
  8.         //below code throws divide by zero exception  
  9.        int data=25/0;    
  10.        System.out.println(data);    
  11.       }   
  12.   
  13.       //handles the Arithmetic Exception / Divide by zero exception  
  14.       catch(ArithmeticException e){  
  15.         System.out.println("Exception handled");  
  16.         System.out.println(e);  
  17.       }   
  18.   
  19.       //executes regardless of exception occured or not   
  20.       finally {  
  21.         System.out.println("finally block is always executed");  
  22.       }    
  23.   
  24.       System.out.println("rest of the code...");    
  25.       }    
  26.     }  

Output:









 

 

 

 

 

 

 


No comments:

Post a Comment