Free Ebook cover Learn to program in complete Java, from programming logic to advanced

Learn to program in complete Java, from programming logic to advanced

3.5

(4)

238 pages

Exception Handling and the Exception Hierarchy in Java: Creating Custom Exceptions

Capítulo 108

Estimated reading time: 4 minutes

Audio Icon

Listen in audio

0:00 / 0:00

17.6 Exception Handling and the Exception Hierarchy in Java

Exception handling is a fundamental aspect of programming in Java, as it allows a program to deal with abnormal situations in a controlled way. An exception is an event that occurs during the execution of a program and that interrupts the normal flow of instructions. Java provides a robust exception handling system that helps you create more reliable and maintainable programs.

Exception Hierarchy in Java

In Java, all exception classes are descendants of the Throwable class. From there, there are two main subclasses: Error and Exception. Errors are rare situations that are not expected to be caught or handled by the program, such as Java virtual machine (JVM) problems. Exceptions are conditions that an application might want to catch.

Exceptions in Java are categorized into two large groups:

  • Checked Exceptions: These are exceptions that need to be handled or declared in the code. They are checked at compile time. Examples include IOException and SQLException.
  • Unchecked Exceptions: These are exceptions that do not necessarily need to be handled or declared. They are checked at run time. Examples include RuntimeException, NullPointerException and ArithmeticException.

Exception handling in Java is mainly done through four keywords: try, catch, finally and throw .

Creating Custom Exceptions

Although Java provides many exception classes that cover a wide range of error situations, it is sometimes necessary to create custom exceptions. This is done by extending the Exception class or any of its subclasses.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

To create a custom exception:

  1. Create a new class that inherits from Exception or RuntimeException, depending on whether you want a checked or unchecked exception.
  2. Add a constructor that accepts an error message as a parameter and passes that message to the base class constructor.
  3. Optionally, you can add other constructors or methods as needed for your exception.

Example of a custom exception:


public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

To throw this exception, you use the throw keyword:


public void someMethod() throws CustomException {
    if (someCondition) {
        throw new CustomException("Error description");
    }
}

To catch this exception, you can use a try-catch block:


try {
    someMethod();
} catch (CustomException e) {
    System.out.println(e.getMessage());
}

Good Practices in Exception Handling

When it comes to creating and using custom exceptions, there are several best practices to follow:

  • Use custom exceptions sparingly: Before creating a new custom exception, consider whether one of Java's standard exceptions can be used.
  • Provide informative error messages: Error messages should provide sufficient detail so that the problem can be identified and resolved.
  • Document exceptions: If a method can throw a custom exception, it should be clearly documented so that users of the class know what to expect.
  • Do not use exceptions for flow control: Exceptions should be used for error conditions and not as a form of normal program flow control.
  • Avoid catching the generic Exception class: This may accidentally catch exceptions you didn't intend to handle.

In summary, exception handling and creating custom exceptions are powerful tools in Java that help you create robust and reliable programs. By following best practices and understanding the exception hierarchy, programmers can write code that effectively handles unexpected situations and improves the overall quality of the software.

Now answer the exercise about the content:

Which of the following statements about exception handling in Java is correct?

You are right! Congratulations, now go to the next page

You missed! Try again.

The Throwable class is indeed the superclass of all exceptions in Java, and both Error and Exception subclasses derive from it. Option 3 describes this relationship correctly.

Next chapter

Exception handling and the exception hierarchy in Java: Methods and the throws clause

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.