Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com

Exception Handling in Java

Exception Handling, Hierarchy of Exception classes,Types of Exception ,Exception Example ,Scenarios where an exception may occur

 

Exception Handling in Java

  1. Exception Handling
  2. Advantage of Exception Handling
  3. Hierarchy of Exception classes
  4. Types of Exception
  5. Exception Example
  6. Scenarios where an exception may occur

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.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions.

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When an exception occurs, the program throws an object called an exception object, which contains information about the type of exception that occurred and where it occurred in the program. The Java runtime system handles the exception object and decides what to do with it.

There are two types of exceptions in Java:

  1. Checked exceptions: These are exceptions that the compiler checks to ensure that they are handled properly. If a method throws a checked exception, the calling method must handle it using a try-catch block or declare that it throws the exception using the throws keyword.

  2. Unchecked exceptions: These are exceptions that are not checked by the compiler. They occur at runtime and are typically caused by programming errors such as null pointer dereferences, division by zero, or out-of-bounds array accesses.

To handle an exception in Java, you can use a try-catch block. Here is an example:

java
try { // code that might throw an exception } catch (ExceptionType e) { // code to handle the exception }

In this example, you place the code that might throw an exception inside the try block. If an exception occurs, the code inside the catch block is executed. The ExceptionType is the type of exception that you want to catch. If you want to catch all types of exceptions, you can use the Exception class.

You can also use a finally block to ensure that some code is executed whether or not an exception occurs:

java
try { // code that might throw an exception } catch (ExceptionType e) { // code to handle the exception } finally { // code that is always executed }

In this example, the code inside the finally block is executed whether or not an exception occurs.

Java provides several built-in exception classes such as ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, and IOException. You can also define your own exception classes by extending the 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:

  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. 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:

hierarchy of exception handling

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

hierarchy of exception handling

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes each.

KeywordDescription
tryThe "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.
catchThe "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finallyThe "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
throwThe "throw" keyword is used to throw an exception.
throwsThe "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.

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

  1. public class JavaExceptionExample{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.       //code that may raise exception  
  5.       int data=100/0;  
  6.    }catch(ArithmeticException e){System.out.println(e);}  
  7.    //rest code of the program   
  8.    System.out.println("rest of the code...");  
  9.   }  
  10. }  

Test it Now

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.

Post a Comment

© JAVA. The Best Codder All rights reserved. Distributed by