top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Exception Handling In Java

Exception handling is a crucial aspect of writing robust and reliable Java applications. It allows us to gracefully manage unexpected situations that may occur during program execution.


What is Exception Handling?


In Java, an exception is an event that disrupts the normal flow of a program's instructions. It is an object which is thrown at runtime.

Exception handling is the process of responding to and managing these exceptional events. It provides a way to separate error-handling code from regular code, making programs easier to read, understand, and maintain.


Why is Exception Handling Important?


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 these 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;  

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.


We use exception handling to:

  1. Prevents program crashes: Without exception handling, unexpected errors can cause our program to terminate abruptly.

  2. Improves user experience: Properly handled exceptions can provide meaningful error messages to users.

  3. Enhances debugging: Exception handling makes it easier to identify and fix issues in our code.

  4. Increases reliability: By anticipating and handling potential errors, our application becomes more robust.


Types of Exceptions:


Checked: Checked exceptions are exceptions that are checked at compile-time. The Java compiler requires that these exceptions be either caught or declared in the method signature using the throws keyword.

  • It Must be handled using try-catch blocks or declared with the throws keyword.

  • Typically used for conditions that are outside the control of the program, such as file I/O errors, network issues, or database errors.

  • And it derives from the Exception class but not from the RuntimeException class.


Unchecked: Unchecked exceptions are exceptions that are not checked at compile-time. The compiler does not require these exceptions to be caught or declared.

  • It Does not need to be explicitly handled using try-catch blocks or declared with the throws keyword.

  • Typically used for programming errors, such as logic errors or improper use of an API.

  • They derive from the RuntimeException class.


Error: Errors indicate unrecoverable system issues beyond program control. such as running out of memory or a system crash. Since errors are generally caused by problems that cannot be recovered from, it’s usually not appropriate for a program to catch errors. Instead, it is usually practice to log the error and exit the program.


Key Components of Java Exception Handling:

1.          try: The block of code where exceptions might occur.

  

try {    // code that may throw an exception

} catch (ExceptionType e) {

    // code to handle the exception

}

2.          catch: The block of code that handles the exception thrown by the try block. Multiple catch blocks can be used to handle different types of exceptions.

 

catch (IOException e) {  

 // handle IOException

} catch (SQLException e) {  

 // handle SQLException

}

3.          finally: An optional block that executes regardless of whether an exception was thrown or not, typically used for cleanup activities.

 

finally {  

 // cleanup code

}

4.          throw: Used to explicitly throw an exception.

throw new ExceptionType ("Exception message"); 

 

5.          throws: The throws keyword is used in the method signature to declare that the method might throw exceptions.

public void method () throws ExceptionType {  

 // method code

}


How Does Java Handle Exception?


Java catches the exception using the try-catch block. When an exception occurs in the try block, the control is transferred to the corresponding catch block. If no catch block matches the exception type, the JVM looks for the catch block in the calling method, and this process continues up the call stack.


  • Java exception handling is managed via these five keywords: trycatchthrowthrows, and finally. So  how they work? Program statements that we think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. our code can catch this exception (using catch block) and handle it in some rational manner.

  • System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, we use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause.

  • Any code that absolutely must be executed after a try block completes is put in a finally block.


What Happens Inside the JVM and Memory When an Exception Occurs?


When an exception is thrown, the JVM performs the following steps:

1.          Object Creation: When an exception occurs, an exception object is created, encapsulating details about the error.

2.          Stack Unwinding: The JVM searches for a suitable catch block by moving up the call stack from the point where the exception was thrown.

3.          Garbage Collection: After handling the exception, the JVM marks the exception object and other unused objects for garbage collection, freeing up memory resources.

This process ensures that the application doesn’t leak memory and resources are managed efficiently.


Exception Hierarchy

 

All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.

 Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE).



Example of Exception Handling in Java:


Java uses a try-catch block for exception handling.  


public class Example {

  public static void main(String[] args) {

try {

    int[] myNumbers = {1, 2, 3};

    System.out.println(myNumbers[10]);

  } catch (Exception e) {

    System.out.println("Something went wrong.");

    }

}


Multiple Catch Blocks:

You can have multiple catch blocks to handle different types of exceptions:


public class MultipleExceptionsExample {

    public static void main(String[] args) {

        try {

            int[] numbers = {1, 2, 3};

            System.out.println(numbers[3]);  // This will throw an ArrayIndexOutOfBoundsException

        } catch (ArithmeticException e) {

            System.out.println("Arithmetic Exception occurred");

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println("Array Index Out Of Bounds Exception occurred");

        } catch (Exception e) {

            System.out.println("Some other exception occurred");

        }

    }

}


The Finally Block:

The finally block is used to execute code that should run regardless of whether an exception occurs or not:

public class FinallyExample {

    public static void main(String[] args) {

        try {

            int result = 10 / 0;

            System.out.println("Result: " + result);

        } catch (ArithmeticException e) {

            System.out.println("Error: Cannot divide by zero");

        } finally {

            System.out.println("This will always execute");

        }

    }

}


Throwing Exceptions:

We can also throw exceptions explicitly using the throw keyword:

public class ThrowExample {

static void checkAge(int age) {

             if (age < 18) {

               throw new ArithmeticException("Access denied - You must be at least 18 years old.");

             }

             else {

               System.out.println("Access granted - You are old enough!");

             }

           }

 

           public static void main(String[] args) {

             checkAge(15);


Custom Exceptions:

We can create your own exception classes by extending the Exception class:

The throw statement allows us to create a custom error. It is used together with an exception type.

 Syntax:


public class CustomException extends Exception {


    public CustomException(String message) {


        super(message);

    }

}

Usage:

try {    

throw new CustomException("This is a custom exception");

} catch (CustomException e) {

    System.out.println(e.getMessage());

}


Example:

class InsufficientFundsException extends Exception {

    public InsufficientFundsException (String message) {

        super(message);

    }

}


public class BankAccount {

    private double balance;

 

    public void withdraw (double amount) throws InsufficientFundsException {

        if (amount > balance) {

            throw new InsufficientFundsException ("Not enough balance");

        }

        balance -= amount;

    }

 

    public static void main(String[] args) {

        BankAccount account = new BankAccount();

        try {

            account.withdraw(100);

        } catch (InsufficientFundsException e) {

            System.out.println("Transaction failed: " + e.getMessage());

        }

    }

}


Lets understand this example:

1.      InsufficientFundsException class:

o   It extends Exception, making it a checked exception.

o   It has a constructor that takes a String message and passes it to the superclass constructor using super(message).

2.      BankAccount class:

o   The withdraw method declares that it can throw an InsufficientFundsException using the throws keyword in its signature.

o   Inside the method, we create and throw a new InsufficientFundsException with a descriptive message when the withdrawal amount exceeds the balance.

3.      In the main method:

o   We use a try-catch block to handle the potential InsufficientFundsException.

o   If the exception is thrown, we catch it and print the error message.

With these changes, the code should compile and run without errors. When you try to withdraw more money than the account balance, it will throw the InsufficientFundsException, which is then caught and handled in the main method.

This implementation demonstrates proper use of custom exceptions in Java:

·       The custom exception extends Exception.

·       The method that might throw the exception declares it in its signature.

·       The exception is thrown when a specific condition is met.

·       The calling code handles the exception using a try-catch block.


Output:


Insufficient funds: you need $100.0 but have only $0.0


1.      We create a new BankAccount object. The initial balance is $0.

2.      We attempt to withdraw $100 from the account.

3.      Since the balance ($0) is less than the withdrawal amount ($100), an InsufficientFundsException is thrown.

4.      The exception is caught in the catch block.

5.      We print the exception message using e.getMessage(), which returns the string we passed when creating the exception.

This output demonstrates that:

  • The exception is successfully thrown when trying to withdraw more money than is available in the account.

  • The custom exception message correctly includes the amount requested and the current balance.

  • The exception is properly caught and its message is displayed.


Best Practices for Java Exception Handling:


Catch Specific Exceptions:  Catch specific exceptions instead of a generic Exception to handle different error types appropriately.

Avoid Empty Catch Blocks:  Always provide meaningful handling code or log the error.

Use Finally for Cleanup:  Ensure resources like files and database connections are closed properly.

Document Exceptions:  Use JavaDoc to document the exceptions a method might throw.

Avoid Exception Swallowing:  Don’t catch exceptions without handling them or rethrowing.





 

27 views0 comments

+1 (302) 200-8320

NumPy_Ninja_Logo (1).png

Numpy Ninja Inc. 8 The Grn Ste A Dover, DE 19901

© Copyright 2022 by NumPy Ninja

  • Twitter
  • LinkedIn
bottom of page