Exception Handling in Java
Exception handling in Java is an important aspect of programming. Java provides several built-in exception classes to handle common types of errors. Programmers can also create their own custom exceptions.
In this blog, we will explore topics related to exception handling in Java. Knowing the basics of Java is recommended to understand the following questions better.
Introduction
An exception is a disruptive occurrence during run time or when a program is being performed. It stops the typical flow of the program’s instructions. When an exception occurs inside a method, an object is created. It provides information about the exception, including its name, description, and state.
One of the most efficient ways to deal with runtime failures in Java is through exception handling. It helps maintain the application’s normal flow. With the help of exception handling, runtime problems like ClassNotFoundException, IOException, SQLException, RemoteException, etc., can be resolved.
Types of Exceptions in Java
Exception handling in Java is of two types: checked exceptions and unchecked exceptions.
- Checked Exceptions: These are exceptions that the programmer must handle explicitly. The calling method must either handle the exception or declare it throws an exception using the throws keyword.
Examples of checked exceptions in Java include:
- IOException
- ClassNotFoundException
- SQLException
- Unchecked Exceptions: These exceptions do not need to be handled explicitly by the programmer. They are also known as runtime exceptions because they are thrown at runtime when something unexpected happens.
Examples of unchecked exceptions in Java include:
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArithmeticException
Additionally, Java also provides a hierarchy of exception classes. Developers can use these to handle specific types of exceptions. Some commonly used exception classes in Java include:
- Exception: The base class for all exceptions.
- RuntimeException: The base class for all unchecked exceptions.
- NullPointerException: This exception is thrown when a program attempts to use a null object reference.
- IllegalArgumentException: This exception is thrown when a method receives an invalid argument.
- IOException: This exception is thrown when an I/O operation fails.
Developers can also create their custom exception classes by extending the Exception class. It allows developers to create specific exception types for their programs and handle them appropriately. To learn more about exception handling you can also pursue a Core Java course that will help you get more clarity.
Exception Handling in Java With Examples
Example 1: Handling a Checked Exception
In this example, we will use a try-catch block to handle a checked exception. The FileReader constructor throws an IOException, so we must handle it by catching the exception.
import java.io.FileReader;import java.io.IOException; public class ExceptionHandlingExample { public static void main(String[] args) { try { FileReader reader = new FileReader(“file.txt”); } catch (IOException e) { System.out.println(“An error occurred: ” + e.getMessage()); } }} |
In this example, if the file.txt file does not exist or cannot be read, the FileReader constructor will throw an IOException. The catch block will handle the exception and print an error message to the console.
Example 2: Handling an Unchecked Exception
In this example, we will use a try-catch block to handle an unchecked exception. The parseInt method of the Integer class throws a NumberFormatException if it passed a non-numeric string.
public class ExceptionHandlingExample { public static void main(String[] args) { try { int num = Integer.parseInt(“abc”); } catch (NumberFormatException e) { System.out.println(“An error occurred: ” + e.getMessage()); } }} |
In this example, the parseInt method is passed the string “abc”, which is not a valid integer. This will cause the method to throw a NumberFormatException. The catch block will handle the exception and print an error message to the console.
Example 3: Using a Finally Block
In this example, we will use a Finally block to execute some code regardless of whether an exception is thrown or not. The Finally block is useful for releasing resources or cleaning up after an operation.
import java.io.FileReader;import java.io.IOException; public class ExceptionHandlingExample { public static void main(String[] args) { FileReader reader = null; try { reader = new FileReader(“file.txt”); // do something with the reader } catch (IOException e) { System.out.println(“An error occurred: ” + e.getMessage()); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { System.out.println(“An error occurred: ” + e.getMessage()); } } }} |
In this example, the FileReader is opened in the try block. The Finally block contains code that executes, regardless of whether an exception is thrown or not. In this case, the code in the Finally block releases the resources used by the FileReader by calling the close method. If an exception is thrown, the Finally block will still be executed.
Custom Exception in Java
Java allows you to derive your own exception class from the base class Exception. Custom Exceptions are things users create themselves. Basically, custom Java exceptions are used to customize exceptions to your requirements.
Here is an example of how to create a custom exception in Java:
public class CustomException extends Exception { public CustomException() { super(“This is a custom exception.”); } public CustomException(String message) { super(message); }} |
In this example, we have created a custom exception called CustomException. This exception extends the Exception class, which is the base class for all exceptions in Java.
Here, a string that can be acquired using the getMessage() function on the object we generated has been provided to the function Object() { [native code] } of the superclass, the Exception class.
We defined two constructors in the CustomException class. The first constructor takes no arguments. It calls the constructor of the Exception class with the standard error message. The second constructor takes a string argument that the user can use to provide a custom error message.
To use this custom exception in our code, we can throw it like any other exception:
public class CustomExceptionExample { public static void main(String[] args) { try { throw new CustomException(“This is a custom exception.”); } catch (CustomException e) { System.out.println(e.getMessage()); } }} |
In this example, we have thrown a CustomException with a custom error message. When the exception is caught in the catch block, the error message is printed to the console.
Custom exceptions are useful for providing more specific information about errors. They distinguish between different types of errors in your code. By extending the Exception class, you can create custom exceptions that behave like Java’s built-in exceptions.
User Defined Exception in Java
User-defined exceptions are custom exceptions created by programmers to represent specific kinds of errors or exceptions in their code. They are created by extending one of the exception classes provided by Java, such as Exception or RuntimeException. Here’s an example of how to create a user-defined exception in Java:
public class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); }} |
In this example, we have created a user-defined exception called InvalidAgeException that extends the Exception class. It represents an error that occurs when a user’s age is outside of a valid range.
The InvalidAgeException class defines a constructor that takes a String argument. The String argument provides a custom error message. This constructor calls the Exception class’s constructor with the provided message.
To use this user-defined exception in our code, we can throw it like any other exception:
public class UserDefinedExceptionExample { public static void main(String[] args) { try { int age = 150; if (age < 0 || age > 120) { throw new InvalidAgeException(“Invalid age: ” + age); } System.out.println(“Age: ” + age); } catch (InvalidAgeException e) { System.out.println(e.getMessage()); } }} |
The user-defined exception we have produced in this example is called InvalidAgeException. Then, we check the user’s age in our code to see if it falls within a valid range using this exception. We throw an InvalidAgeException with a specific error message if the age is outside the acceptable range. The error message is printed to the console when the exception is caught in the catch block.
User-defined exceptions can be useful when you want to provide specific information about an error or exceptional condition in your code. By extending one of the exception classes, you can create custom exceptions similar in behavior to the built-in exceptions in Java.
Conclusion
Understanding exception handling in Java is an essential part of creating robust and reliable programs. Exceptions are used to handle unexpected or exceptional conditions that occur during program execution. Therefore, it is an important concept in Java programming.