In Java , exception handling is a process to handle runtime errors and to ensure the continuty of program’s normal flow after unexpected event .
Java Exception Hierarchy and Types :
All Java exceptions and errors are subclasses of Throwable class . Throwable class has two main subclasses which are Errors and Exceptions.
- Errors : In Java , errors refer to a serious class of problems that are unrecoverable by the program itself which are often related to JVM or system resources .
- Exceptions : Java exceptions are the conditions that can be handled by the application. Exceptions are further divided into two categories :
1. Checked Exceptions : Checked exception in Java is an exception that compiler forces the programmer to handle explicitly . These checked exceptions are typically caused by conditions outside the control of the program . E.g. IOExceptions , ClassNotFoundException, FileNotFoundException etc .
2. Unchecked Exceptions ( Runtime Exceptions ) : Java unchecked exceptions are exceptions that are not checked by the compiler at compile-time , which means programmer is not required to handle these exceptions explicitly using try-catch block or declare with throws keyword . These unchecked exceptions are subclasses of the java.lang.RuntimeException class . E.g. NullPointerException , ArrayIndexOutOfBoundsException , ArithmeticException etc.
Java Exception Handling Mechanism and Keywords:
Java provides many keywords for Exception Handling:
- try : try block is a block inside which that code is written which need to be tested for exception during execution .
- catch : A catch block is a block of code which handles specific type of exception if it occurs within try block . Multiple catch blocks can be used for different exception types .
- finally : finally is a optional block of code that always executes after try and catch blocks , regardless of whether an exception is handled or not . finally block is commonly used for cleanup tasks like closing resources such as files , network connections etc .
- throw : throw keyword is used to explicitly throw a single exception instance from a method or block of code .
- throws : throws keyword is used in a method signature to declare which checked exceptions the method might throw by informing the caller to handle them.
Basic try-catch Example :
- The try block contains code that might throw an exception
- The catch block handles the exception if it occurs
Example :
class Hello {
public static void main (String args[] ) {
int a =65;
int b=0;
try {
int res=a/b ;
System.out.println(“Result is : “ +res);
} catch (ArithmeticException e ) {
System.out.println(“Error:Division by 0!”);
}
}
}
Output :
Error: Division by 0!
Rules For Defining try & catch block:
- Inside the try block enclose the problem creating statement .
- Inside the catch block enclose the exception handling statement .
- Inside the try block where ever the statement has the problem , then control will be transfer to handle the problem inside catch block . After handling the problem in catch block, then only other statements executes.
- Between try and catch block no statements are allowed.
- Always catch block has to be followed with the try block only . Without try block , one shouldn’t provide the catch block .
- try block can be declared with one or more catch blocks.
- Inside the try block if problem is occured at the first or second statement , then control will be transferred to catch block to handle the exception and other statements of try block will not execute .
- If there is no problem in try block, then catch block will not execute.
- Between multiple catch blocks no other statements are allowed
- While declaring multiple catch blocks , the order should from subtype to super type .
Java Exception Hierarchy :
In Java , all exceptions and errors are subclasses of the Throwable class. It has two main branches:
- Exception
- Error
The below figure demonstrate the exception hierarchy in Java:
Types of Java Exceptions :
Java defines several types of exceptions . Below diagram demonstrate the types of Exceptions in Java.
- Built-in Exception :
Built-in Exceptions are pre-defined exception classes provided by Java to handle common exceptions during program execution . There are two types of built-in exceptions in java.
- Checked Exception : Checked exception in Java is an exception that compiler forces the programmer to handle explicitly . These checked exceptions are typically caused by conditions outside the control of the program . E.g. IOExceptions , ClassNotFoundException, FileNotFoundException etc .
Unchecked Exceptions ( Runtime Exceptions ) : Java unchecked exceptions are exceptions that are not checked by the compiler at compile-time , which means programmer is not required to handle these exceptions explicitly using try-catch block or declare with throws keyword . These unchecked exceptions are subclasses of the java.lang.RuntimeException class . E.g. NullPointerException ,ArrayIndexOutOfBoundsException , ArithmeticException etc.
2. User-Defined Exception : Sometimes, the built-in exceptions in Java are not able to describe a certain situation . In such cases, users can create exceptions, which are called ” User -Defined Exception ” .
Methods to Print the Exception Information :
- printStackTrace() : Prints the full stack trace of the exception, which include name , message and location of the error .
- toString() : This method prints the exception information in the format of the Name of the Exception.
- getMessage() : This method prints the description of the exception.
Difference between Java Exception and Error :
| Feature | Exception | Error |
|---|---|---|
| Definition | An event that occurs during java program execution which disrupt the normal flow of the program and which can be handle using try-catch. | Java error is a serious problem that occurs in the JVM ,which generally cannot be handled by the application. |
| Package | Java Exception class is present in java.lang.Exception package | Error class is present in java.lang.Error package |
| Handling | Java exceptions can be caught and handled. | Java errors are usually not recoverable. |
| Examples | IOException, SQLException, ArithmeticException, NullPointerException | OutOfMemoryError, StackOverflowError |
