Exception Handling in Java with Examples

Exception Handling in Java with Examples

Exception Handling in Java

Exception handling in Java allows developers to deal with unexpected issues or errors that may occur during program execution.

What is an Exception in Java?

  • An exception in Java is an event that occurs during the execution of a program, disrupting the normal flow of instructions.
  • It represents an error or an unexpected situation that needs to be handled.
  • Exceptions can occur for various reasons, such as invalid input, file not found, or division by zero.

Difference between an Error and an Exception in Java

Errors are usually caused by things outside the program's control, like running out of memory or the computer crashing.
Exceptions are things the program can anticipate, like trying to divide a number by zero or reading a file that doesn't exist.

Types of Exception Handling in Java

  • Java Checked Exceptions
  • Java Unchecked Exceptions
  • Java User-Defined Exceptions

Java Checked Exceptions

  • Checked exceptions are a category of exceptions that are checked by the compiler at compile-time.
  • These exceptions are typically associated with external factors or conditions that a program might encounter during its execution.
  • Some examples are "IOException" and "SQLException".
1import java.io.*;
2
3public class FileDemo {
4    public static void main(String[] args) {
5// Attempt to open a file (This may throw an IOException)
6try {
7  FileReader fileReader = new FileReader("example.txt");
8  // Code to read the file goes here
9  } catch (IOException e) {
10    // Handle the exception
11System.out.println("An error occurred while reading the file: " + e.getMessage());
12        }
13    }
14}

Java Unchecked Exceptions

  • Unchecked exceptions are a category of exceptions that are not checked at compile-time.
  • Also known as runtime exceptions, these exceptions are subclasses of the RuntimeException class.
  • Unchecked exceptions can occur without prior notice and do not require explicit handling.
  • Examples include 'NullPointerException' and 'ArrayIndexOutOfBoundsException.'
1public class NullPointerExceptionDemo {
2public static void main(String[] args) {
3  String text = null; // Assigning null to a string
4  
5  try {
6    int length = text.length(); 
7  // This line will throw a NullPointerException
8  } catch (NullPointerException e) {
9    // Handle the exception
10  System.out.println("A NullPointerException occurred: " + e.getMessage());
11        }
12    }
13}

Java User Defined Exceptions

  • In addition to using predefined exceptions, Java allows the creation of custom exceptions by extending the Exception class.
  • These user-defined exceptions enable the design of unique and tailored classes to address specific application needs.

Step 1 Create a Custom Exception Class

1
2class MyCustomException extends Exception {
3    public MyCustomException(String message) {
4        super(message); 
5  // Call the constructor of the parent class
6  (Exception) with a custom error message
7    }
8}
  • Here, we create a custom exception class named MyCustomException by extending the built-in Exception class.
  • The custom exception class includes a constructor that accepts a custom error message and passes it to the constructor of the parent Exception class using super(message).

Step 2 Create a Method that May Throw the Custom Exception

1// Create a method that may throw the custom exception
2
3public static void checkAge(int age) throws MyCustomException {
4  if (age < 18) {
5    // Throw the custom exception when a specific condition is met
6      throw new MyCustomException("not valid");
7    } else {
8      System.out.println("Access granted. You are old enough.");
9    }
10}
  • In this step, we define a method named checkAge that takes an integer parameter representing a person's age.
  • We use the throws MyCustomException declaration to indicate that this method may throw our custom exception.
  • Inside the method, we check if the provided age is less than 18. If it is, we throw our custom exception with a specific error message.
  • If the age condition is not met, we print a message indicating that access is granted.

Step 3 Exception Handling

1public static void main(String[] args) {
2  int userAge = 16; 
3  // Change the age value to test different scenarios
4
5    try {
6        // Call the method that may throw the custom exception within a try-catch block
7        checkAge(userAge);
8    } catch (MyCustomException e) {
9        // Handle the custom exception
10        System.out.println("Access denied: " + e.getMessage());
11    }
12}
13
  • In the main method, we initialize a variable userAge with a value (you can change this value to test different scenarios).
  • Inside a try-catch block, we call the checkAge method, passing the userAge as an argument.
  • If the checkAge method throws our custom exception due to the age condition, the catch block will execute.
  • In the catch block, we handle the custom exception by displaying a custom error message indicating that access is denied.

try catch Exception handling in Java

  • try: A try block is used to catch exceptions that might arise within its scope.
  • Catch: When an exception is thrown, the program flow jumps to the corresponding catch block, allowing for proper exception handling.
  • throw: The throw keyword is employed to specify an exception under certain conditions, allowing for controlled error propagation.
1try {
2    // Here's some code that might generate an exception
3} catch (ExceptionType e) {
4    // Handle the exception
5}
6
7if (someCondition) {
8    throw new CustomException("Custom exception message");
9}
  • finally: The finally block acts as a safety net for code that must run regardless of whether an exception occurs. It's often used to perform cleanup tasks, such as closing resources.
1try {
2    // Here's some code that might generate an exception
3} catch (ExceptionType e) {
4    // Handle the exception
5} finally {
6    // Cleanup code or tasks that must be executed
7}

How Does JVM Handle an Exception

  • Java Virtual Machine (JVM) plays a crucial role in handling exceptions. When an exception occurs, the JVM looks for a block of code that can handle it.
  • This block of code is known as a 'catch' block. If the JVM finds a matching 'catch' block, it transfers control to that block for further processing.

Pros of Exception Handling

  • Separation of Concerns - Exception handling separates error-handling code from standard program logic. This enhances code readability and maintainability.
  • Debugging Aid: - Exceptions provide valuable information about the cause of an error, including a stack trace that shows where the error occurred.

Cons of Exception Handling

  • Complexity - Handling exceptions can lead to complex code structures, especially in programs with extensive error-checking and multiple try-catch blocks.
  • Overuse - Overusing exceptions for control flow, also known as "exception abuse," can lead to poor coding practices.

Conclusion

Exception handling in Java is vital for robust applications. Differentiate between checked and unchecked exceptions, use user-defined exceptions, and apply try, catch, throw, and finally for graceful error handling and smooth code execution.