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:
- statement 1;
- statement 2;
- statement 3;
- statement 4;
- statement 5;//exception occurs
- statement 6;
- statement 7;
- statement 8;
- statement 9;
- 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
- public class JavaExceptionExample{
- public static void main(String args[]){
- try{
- //code that may raise exception
- int data=100/0;
- }catch(ArithmeticException e){System.out.println(e);}
- //rest code of the program
- System.out.println("rest of the code...");
- }
- }
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
- try{
- //code that may throw an exception
- }catch(Exception_class_Name ref){}
Syntax of try-finally block
- try{
- //code that may throw an exception
- }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
- public class TryCatchExample1 {
-
- public static void main(String[] args) {
-
- int data=50/0; //may throw exception
-
- System.out.println("rest of the code");
-
- }
-
- }
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
- public class TryCatchExample2 {
-
- public static void main(String[] args) {
- try
- {
- int data=50/0; //may throw exception
- }
- //handling the exception
- catch(ArithmeticException e)
- {
- System.out.println(e);
- }
- System.out.println("rest of the code");
- }
-
- }
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
- class TestFinallyBlock {
- public static void main(String args[]){
- try{
- //below code do not throw any exception
- int data=25/5;
- System.out.println(data);
- }
- //catch won't be executed
- catch(NullPointerException e){
- System.out.println(e);
- }
- //executed regardless of exception occurred or not
- finally {
- System.out.println("finally block is always executed");
- }
-
- System.out.println("rest of phe code...");
- }
- }
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
- 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);
- }
- //cannot handle Arithmetic type exception
- //can only accept Null Pointer type exception
- 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...");
- }
- }
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
- public class TestFinallyBlock2{
- public static void main(String args[]){
-
- try {
-
- System.out.println("Inside try block");
-
- //below code throws divide by zero exception
- int data=25/0;
- System.out.println(data);
- }
-
- //handles the Arithmetic Exception / Divide by zero exception
- catch(ArithmeticException e){
- System.out.println("Exception handled");
- 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...");
- }
- }
Output:
No comments:
Post a Comment