Exception Handling in Java - Javastudypoint

Saturday, January 5, 2019

Exception Handling in Java

Exception Handling in Java is one of the most powerful features that allow us to handle the runtime error so that the normal flow of the program can be maintained. In this tutorial, we will learn What is an exception, Types of exception, exception classes, how to handle the exception in Java, and the difference between error and exception. Before discussing exception handling in java in detail lets first understand What is an exception.


What is an Exception?

Exceptions in Java are the any abnormal, unwanted events, or extraordinary conditions that may occur at runtime. It interrupts the normal flow of the program. Exception terminated the program execution. When an exception occurs we get a system generated an error message. The good news is that exceptions can be handled in Java. Therefore we can provide a meaningful message to the user rather than the system generated an error message, which not understandable to a user.

Why an Exception occurs?

Exceptions in Java can occur due to the following reasons: 
  • Wrong data entered by the user.
  • Network Connection problem.
  • Hardware problem.
  • Opening a file which is not existing in your program.
  • Server down problem. 



What is Exception Handling in Java?

Exception Handling in Java is a powerful mechanism that is used to handle the runtime errors, compile-time errors are not handled by exception handling in Java. If an exception occurs in your code (suppose in line 6), then the rest of the code is not executed. Therefore Java compiler creates an exception object and this exception object directly jump to the default catch mechanism. Where there is a default message which is print on the screen and our program gets terminated.

Advantages of Exception Handling in Java:

It maintains the normal flow of the program. Suppose in your program there are many statements and an exception occurs in midway then the statements after the exception will not execute and the program will terminate and we get system generated error message. Which are not understandable to a user. 

By exception handling mechanism all the statements in your program will execute and do not break the normal flow of the program and it generated a user-friendly message rather than the system generated an error message. 

Difference between exception and errors:

Errors: Most of the times errors are not caused by our programs these are due to lack of system resources. Errors are not recoverable (not handle).

For example, if OutOfMemory error occurs during the execution of a program we can't do anything and the program will be terminated abnormally.

Exceptions: Exceptions in Java are the any abnormal, unwanted events, or extraordinary conditions that may occur at runtime. Exceptions are caused by our program and exceptions are recoverable.

Few examples of exceptions: ArithmaticException, NullPointerException, ClassNotFoundException, IOException etc.

Java Exception class Hierarchy:

  • Throwable is the parent class of all exception classes in java.
  • Throwable has two child classes: Error and Exception.
  • The Exception class represents the exception that can be handled by our program using try and catch block.
  • RuntimeException is a child class of exception class. These type of exception may occur at runtime. ArithmeticException, NullPointerException etc. is the example of runtime exception.
Exception Handling in Java


Java Exception Handling Keywords:

There are 5 keywords which are used for exception handling in Java:

1. try : 

In java try block we can write the code that might throw an exception. A try block in Java must be followed by either at least one catch block or one finally block.

2. catch:

catch block in Java is used to handle the exception that may occur in our program. It must be used after try block only. We can use more than one catch block with a single try block.

3. finally:

finally block in Java can be used to clean up code or release some resources that are utilized in the program. finally block is always run whether the exception handled or not. 

4. throw:

throw keyword in java can be used to throw an exception. It can throw the exceptions explicitly. We can throw either checked or unchecked exception using throw keyword.

Syntax:   throw exception;

5. throws:

throws keyword in java is used for declaring an exception. We can declare only checked exception using throws keyword. So its programmer responsibility to provide the exception handling code so that the normal flow of the program can be maintained.

Syntax:  return_type method_name() throws exception_class_name.

Types of Exception in Java:

There are two types of Exception in Java:

1) Checked Exception.
2) Unchecked Exception.



1. Checked Exceptions:

All the classes which inherit throwable class except RuntimeException and Error are known as Checked Exception. The checked exceptions are checked by the compiler at compile-time. In case of checked exception if programmers will not handle the exception then we will get a compile-time error. We will handle the checked exception by using a try-catch block or and declare using throws keyword. For example, FileNotFoundException, ClassNotFoundException, IOException, SQLException etc. 


Checked Exception Example:

In this example, we are reading the file abc.txt and displaying its content on the screen. Here we are using FileInputStream for reading the data from a file, throws FileNotFoundException. The read() method which is used for reading the data from the input stream and close() method which is used for closes the file input stream throws an IOException.

import java.io.*;
class ExceptionExample
{
public static void main(String args [])
{
FileInputStream fis = null;

*/ FileInputStream throws 
    FileNotFoundException which 
   is a checked exception.
*/

fis = new FileInputStream("D:/abc.txt");
int i;

*/ read() method of FileInputStream
   class also throws an IOException.
*/
while(( i = fis.read() ) != -1 )
{
System.out.println((char) i); 
}

*/ close() method used for 
   close the file input stream
   it throws an IOException.
*/
fis.close();
}
}

Output:


Exception in thread "main" java.lang.Error: Unresolved compilation problem
Unhandled exception type  FileNotFoundException
Unhandled exception type  IOException Unhandled exception type  IOException

There are two ways to handle this error: 

1) Using try-catch.
2. using throws keyword.


1) Handle Checked Exception using a try-catch block.


It is a good practice to handle the exception using try-catch block Because you should give a meaningful message for each exception type so that it would be easy for someone to understand the error.


import java.io.*;
class ExceptionExample
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("D:/abc.txt");
}
catch(FileNotFoundException fn)
{
System.out.pritnln("The file is not present at given path");
}
int i;
try
{
while(( i = fis.read() ) != -1 )
{
System.out.println((char) i); 
}
fis.close();
}
catch(IOException ie)
{
System.out.println(" IO exception occured: " +ie);
}
}
}

2) Declare the exception using throws keyword:


As we know that checked exception occurs inside the main() method. So you can declare the exception in the main() method using throws keyword. You can declare the exception like this:
public static void main(String args []) throws IOException
IOException is the parent class of FileNotFoundException so that it by default handle the FileNotFoundException


import java.io.*;
class ExceptionExample
{
public static void main(String args []) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("D:/abc.txt");
int i;
while(( i = fis.read() ) != -1 )
{
System.out.println((char) i); 
}
fis.close();
}
}




2. Unchecked Exceptions:

All the classes which inherit RuntimeException are known as Unchecked Exception. The Unchecked exceptions are not checked by the compiler at compile-time. But they are checked at runtime.  In case of Unchecked exception if programmers will not handle the exception then we won't get a compile-time error. Most of the time these exceptions occur due to the wrong data entered by the user ( divide by zero). In such type of exceptions, the compiler will never force you to handle the exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBounds etc.



Example of Unchecked Exception:

In this example, we are dividing two numbers which are entered by the user. If the user enters right data then our program will display division of two numbers. If the user enters wrong data then our program will display ArithmeticException.
These exceptions will not occur at compile-time, it can occur at runtime.

import java.util.*;
class UncheckedException
{
public static void main(String args [])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number:");
int a = sc.nextInt();
System.out.println("Enter the second number:");
int b = sc.nextInt();
int c = a/b;
System.out.println("Division of two number is: " +c);
System.out.println("Program continues!");
}
} 

Output: When a user enters the right data. 


Enter the first number:    12

Enter the second number: 2
Division of two number is: 6 
Program continues! 

Output: When a user enters the wrong data.


Enter the first number:    12

Enter the second number: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero

Let's see another example in this example we are taking an example of an array. Here my array has only 5 elements but we are trying to display the value of the 10th element. 

It should throw an exception ArrayIndexOutOfBoundsException. 

class UncheckedException

{
public static void main(String args [])
{
/* This array has only 5 elements but 
we are trying to display the value of the 10th element. 
It should throw ArrayIndexOutOfBoundsException.
*/
int arr[] = {1,2,3,4,5};
System.out.println("The value of 10th element is:" +arr[10]);
}
}


 Exception handling using try and catch block:

class UncheckedException
{
public static void main(String args [])
{
try
{
System.out.pritnln(12/0);
System.out.println("We are in try block");
}
catch(ArithmeticException e)
{
System.out.println("Exception: " +e.getMessage());
}
System.out.println("Programs continues!");
}
}

Output:

Exception: / by zero.
Program continues!

Multiple catch block in Java:


If we want to perform a different task at the occurrence of different exception then we should go for multiple catch block.

Let's see an example of multiple catch block in Java.

class UncheckedException
{
public static void main(String args [])
{
try
{
int arr [] = new int[5];
arr[3] = 12/0;
System.out.println("We are in try block");
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero exception");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array elements outside limit");
}
catch(Exception e)
{
System.out.println("Other type of exception");
}
System.out.println("We are outside the try catch block");
}


Output:

Divide by zero exception
We are outside the try catch block




Explicitly throw an Exception in Java:


throw keyword in Java can be used to throw an exception. It can throw the exceptions explicitly. We can throw either checked or unchecked exception using throw keyword. Let's understand with a simple example.

In this example, we have created two variable balance and withdrawlAmount. If the balance is less than withdrawalAmount then ArithmeticException has occurred. Therefore we throw an object of ArithmeticException and it will display a message on the screen "insufficient balance".

class ExceptionExample
{
public static void main(String args [])
{
int balance = 5000;
int withdrawlAmount = 6000;

try
{
if(balance < withdrawlAmount)
// created an object of ArithmeticException class
throw new ArithmeticException("Insufficient balance");
balance =  balance-withdrawlAmount;
System.out.println(" Transactions successfully completed");
}
catch(ArithmeticException e)
{
System.out.println("Exception is: " +e.getMessage());
}
System.out.println("Programs continues!");
}
}
Output:

Exception is: Insufficient balance
Programs continues!



Checked Exception vs Unchecked Exception:

  • All the classes which inherit throwable class except RuntimeException and Error are known as Checked Exception while all the classes which inherit RuntimeException are known as Unchecked Exception.

  • The checked exceptions are checked by the compiler at compile-time while the Unchecked exceptions are not checked by the compiler at compile-time. But they are checked at runtime.

  • In case of checked exception if programmers will not handle the exception then we will get a compile-time error while in case of Unchecked exception if programmers will not handle the exception then we won't get a compile-time error.

  • FileNotFoundException, ClassNotFoundException, IOException, SQLException etc. are the example of checked exception while ArithmeticException, NullPointerException, ArrayIndexOutOfBounds etc. are the example of Unchecked exception.

Throw vs Throws in Java:

  • throw keyword in Java can be used to throw an exception. It can throw the exception explicitly while throws keyword in java is used for declaring an exception 

  • A throw is used inside the method while throws are used with the body signature. for example
      public void m1() {   throw new ArithmeticException  } and public void m1()
      { throws IOException, FileNotFoundException. }

  • A throw is used to throw only one exception while we can declare multiple exceptions using throws.

  • A throw is used in either checked exception or unchecked exception while throws only are used in a checked exception.

Final vs Finally vs Finalize in Java:

  • Final is a modifier which is applicable for classes, methods, and variables. If a class declared as final then we can't extend that class, if a method declared as final we can't override that method in the child class, if a variable declared as final we can't change the value of that variable.

  • Finally is a block always associated with try-catch to maintain the cleanup code. finally block is always run whether the exception handled or not. 

  • Finalize() is a method which is always invoked by garbage collector just before destroying an object to perform clean up processing.


You might also like these related topics:

Polymorphism in Java OOPs with Example 
Inheritance in Java OOPs with Example
Abstract class in Java with Example
Constructor in Java with Example
Java Authentication and Authorization Service - JAAS
MVC Architecture in JSP with Example
Life Cycle of a JSP Page
JDBC Driver in Java
Encapsulation in Java OOPs with Example What are Java Beans?





















No comments:

Post a Comment