Handling Exceptions

Introduction

 
An error is a condition that causes a disruption in the execution of the program. An error can be a result of circumstances, such as incorrect code or insufficient memory resources. Errors in a java program are categorized into two types, compile-time error and run-time error. The compile-time error occurs when the syntax of a programming language is not followed. Run-time errors occurs during the execution of a program. Such an error is known as exception. An exception can lead to the termination of an application.
 

Throwable class

 
The throwable class is the base class of execution in Java. It can only throw exception objects that are derived from the Throwable class. Exceptions and errors are derived from the throwable class.
 

Exception class

 
The Exception class represents the conditions that a program should handle. The Exception class has various subclasses, such as classNotFoundException, IllegalAccessException, and RuntimeException.
 
The classNotFound Exception throws when a class is being referred to, but no definition is found.
 

Error class

The Error class defines the exception related to the java run-time environment. For example, OutOfMemoryErrror is an error that occurs when there is insufficient system memory to execute a program.
 

Exceptions

  • Checked Exception
  • Unchecked Exception
Checked Exception
 
There are the invalid conditions that occur in a java program due to the problems, such as accessing a file that does not exist or referring a class that does not exist. The checked exception are the objects of the Exception class or any of its subclass excluding the RuntimeException and Error class.
 
Unchecked Exception
 
The unchecked exception occurs because of programming errors. The compiler does not force a programmer to handle these exceptions. Such errors should be handled by writing bug-free code.
 

Implementing Exception

 
When an unexpected error occurs, Java creates an exception object. After creating the exception object, Java sends it to the program by throwing the exception. The exception object contains information about the type of error and the state of the program when the exception occurred.
  • Try
  • Catch
  • Throw 
  • Throws
  • Finally
  • Try with resources 

Try and Catch

 
A try block encloses the statement that might raise an exception and defines one or more exception handlers associated with it. If an exception is raised within the try block, the appropriate exception handler that is associated with the try block processes the exception.
 
Example
  1. import java.util.Scanner;  
  2. public class Addition {  
  3.     public static void main(String args[]) {  
  4.         int num1, num2, result;  
  5.         String snum1, snum2;  
  6.         Scanner sc = new Scanner(System.in);  
  7.         try {  
  8.             System.out.println("Enter the 1st number");  
  9.             snum1 = sc.next();  
  10.             System.out.println("Enter the 2nd number");  
  11.             snum2 = sc.next();  
  12.             num1 = Integer.parseInt(snum1);  
  13.             num2 = Integer.parseInt(snum2);  
  14.             result = num1 + num2;  
  15.             System.out.println("The result is " + result ");  
  16.             }  
  17.             catch (Exception e) {  
  18.                 System.out.println("Please input only numeric values");  
  19.             }  
  20.         }  
  21.     }  

Throw

 
By using the throw keyword, it can throw an exception explicitly. The throw keyword terminates the normal flow of control of the Java code and stops the execution of subsequent statements. The throw keyword transfers the control to the nearest catch block that handles the type of exception being thrown.
  1. public class ThrowDemo {  
  2.     void display() {  
  3.         throw new RuntimeException();  
  4.     }  
  5.     public static void main(String args[]) {  
  6.         ThrowDemo obj1 = new ThrowDemo();  
  7.         try {  
  8.             obj1.display();  
  9.         } catch (RuntimeException e) {  
  10.             System.out.println("Runtime Exeption raised");  
  11.         }  
  12.     }  
  13. }  

Throws

 
The throw keyword is used by a method to specify the types of exceptions that the method can throw. If a method is capable of raising a checked exception that it cannot handle, then the method must specify that the exception is handled by the calling method. 
  1. public class ThrowsDemo {  
  2.     void display() throws Exception {  
  3.         throw new Exception();  
  4.     }  
  5.     public staic void main(String args[]) {  
  6.         ThrowsDemo obj1 = new throwsDemo();  
  7.         try {  
  8.             obj1.display();  
  9.         } catch (Exception e) {  
  10.             System.out.println("Runtime Exception raised");  
  11.         }  
  12.     }  
  13. }  

Finally

 
During the execution of a Java program, when an exception is raised, the rest of the statements in the try block are ignored. It is necessary to execute certain statements irrespective of whether an exception is raised. The final block is used to execute these required statements.
  1. finally  
  2. {  
  3.  //block of code that is always executed irrespective of an execution being raised or not.   
  4.  }  

Try with Resources

 
The try-with-resources is similar to the try block. It is essentially used to declare and automatically close the objects, such as the file streams and database connections after the execution of the try blocks finishes. The try with resources block ensures that one or more system resources are released when they are no longer required.


Similar Articles