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.
What is Exception in Java?
Exception is an abnormal event happens during the execution of the program and stop the program immediately.
In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. These exceptions can occur for various reasons, such as invalid user input, file not found, or division by zero. When an exception occurs, it is typically represented by an object of a subclass of the java.lang.Exception class.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage 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(TBD)
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:
Types of Java Exceptions(TBD)
In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions. Additionally, there is a third category known as errors.
Error: JVM Cannot handle Error.
Eg. Stackoverflow Error.
Exception: JVM Can handle Exception.
Java provides five keywords that are used to handle the exception. The following table describes each.(TBD)
The try-catch Block
**TRY BLOCK:Exception possible block.
Catch Block:Exception candle block.**
One of the primary mechanisms for handling exceptions in Java is the try-catch block. The try block contains the code that may throw an exception, and the catch block is used to handle the exception if it occurs. Here's a basic example:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}
Handling Multiple Exceptions
You can handle multiple types of exceptions by providing multiple catch blocks, each catching a different type of exception. This allows you to tailor your exception handling logic based on the specific type of exception thrown. Here's an example:
try {
// Code that may throw an exception
} catch (IOException e) {
// Handle IOException
} catch (NumberFormatException e) {
// Handle NumberFormatException
} catch (Exception e) {
// Handle any other exceptions
}
try
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Numbers: ");
int no1 = sc.nextInt();
int no2 = sc.nextInt();
System.out.println(no1/no2);
int[] ar = new int[no2]; //5
for(int i=0; i<ar.length; i++)
System.out.print(ar[i]+" ");
}
catch(NegativeArraySizeException | ArithmeticException |
InputMismatchException | ArrayIndexOutOfBoundsException exc)
{
String msg = exc.getMessage();
System.out.println(msg);
}
The finally Block(TBD)
In addition to try and catch, Java also provides a finally block, which allows you to execute cleanup code, such as closing resources, regardless of whether an exception occurs or not. The finally block is typically used to release resources that were acquired in the try block. Here's an example:
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling code
} finally {
// Cleanup code
}
try
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Numbers: ");
int no1 = sc.nextInt();
int no2 = sc.nextInt();
System.out.println(no1/no2);
int[] ar = new int[no2]; //5
for(int i=0; i<ar.length; i++)
System.out.print(ar[i]+" ");
}
catch(NegativeArraySizeException nase)
{
System.out.println("Check array length");
}
catch(ArithmeticException ae)
{
System.out.println("Check no2");
}
catch(InputMismatchException ime)
{
System.out.println("Give inputs properly. ");
}
catch(ArrayIndexOutOfBoundsException aa)
{
System.out.println("Check loop");
}
catch(Exception e)
{
System.out.println("Something went wrong");
}
finally
{
System.out.println("I'm finally - I will be called always");
}
Ex:if hostar has five login with password(try-catch) and unble to login finally is used to login with QRcode.
It is an alternative way to login
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
Here's a simple Java code example where an ArithmeticException occurs:
File Name: ArithmeticExceptionExample.java
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int dividend = 10;
int divisor = 0;
try {
int result = dividend / divisor; // Division by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
// Additional error handling code can be added here
}
}
}
Output:
Error: Division by zero is not allowed.
Explanation
We have a main() method where we attempt to perform division by zero that is not allowed in arithmetic.
Inside the try block, we perform the division operation dividend / divisor, where divisor is assigned the value of 0.
When the division by zero occurs, an ArithmeticException is thrown. We catch this exception using a catch block specifically for ArithmeticException.
In the catch block, we handle the exception by printing an error message, indicating that division by zero is not allowed. Additional error handling logic can be added here if needed.
A few common exceptions that frequently arise while programming in Java are-
ArithmeticException: This exception occurs in case of any unfavorable arithmetic condition e.g. when we divide an integer with zero.
ArrayIndexOutOfBoundsException: This exception occurs when we try to access a non-existent index of an array.
NumberFormatException: This exception occurs when we try to convert a string to any numeric value, but the string format is illegal and cannot be converted.
StringIndexOutOfBoundsException: Similar to the ArrayIndexOutOfBounds exception, this exception arises when a non-existent string index is accessed.
NullPointerException: This exception occurs when we an object with the value “null”.
ClassCastException: This exception occurs when we try to improperly convert a class from one type to another.
IllegalArgumentException: This exception occurs when we pass an illegal or inappropriate argument to a method.
IOException:This exception occurs when there has been a failure in the input/output operations.
ClassNotFoundException: This exception occurs when the specified class cannot be found in the classpath.
FileNotFoundException: This exception occurs when an attempt to open a file denoted by a specified pathname has failed.
EmptyStackException: This exception arises when the pop/peek operation is performed on an empty stack.
Reference:https://www.tpointtech.com/exception-handling-in-java
Top comments (0)