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

Structure of classes and objects in Java: Exception Handling

Capítulo 73

Estimated reading time: 5 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

11.15. Structure of Classes and Objects in Java: Exception Handling

In the world of Java programming, the concept of exceptions is fundamental for the development of robust and reliable applications. Exceptions are events that occur during the execution of a program that interrupt the normal flow of instructions. Exception handling in Java is a mechanism that allows the programmer to deal with these events in a controlled manner, without the program ending abruptly.

Understanding Exceptions

An exception in Java is an object that is thrown, or "thrown", when an error occurs. The base class for all exceptions is Throwable, which is divided into two main subclasses: Error and Exception. Errors are serious situations that should not normally be handled by the application, such as problems in the Java virtual machine (JVM). Exceptions are conditions that the application must try to handle.

Types of Exceptions

Exceptions in Java are categorized into two large families: checked exceptions and unchecked exceptions. Checked exceptions are those that are checked at compile time, and the programmer is required to handle them. Unchecked exceptions, which include the RuntimeException and Error subclasses, do not need to be explicitly handled.

Exception Handling

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

  • try: A try block is used to define a block of code in which exceptions can occur. The block is followed by one or more catch blocks.
  • catch: A catch block is used to handle the thrown exception. There can be multiple catch blocks to handle different types of exceptions.
  • finally: The finally block is optional and is executed after the execution of the try and catch blocks, regardless of a exception was thrown or not. It is commonly used to free up resources, such as closing database connections or files.
  • throw: The throw keyword is used to explicitly throw an exception, whether it is a new instance or an exception that has been caught.

Example of Exception Handling

Let's look at a simple example of how exception handling works in Java:

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

        
public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int division = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        } finally {
            System.out.println("Block finally executed.");
        }
    }
}
        
    

In the example above, the code tries to perform division by zero, which throws an ArithmeticException. The catch block catches this exception and prints an error message. Regardless of whether an exception is thrown or not, the finally block will be executed, printing its message.

Throwing Exceptions

In addition to handling exceptions, you can also throw your own exceptions using the throw keyword. This is useful when you want to create custom error conditions in your methods.

        
public void doSomething(int value) throws CustomException {
    if (value < 0) {
        throw new CustomException("Value cannot be negative");
    }
    // Rest of the code
}
        
    

In the example above, if the value passed to the fazerAlgo method is negative, a new custom exception CustomException is thrown with an explanatory message.

Good Practices in Exception Handling

When dealing with exceptions in Java, it is important to adopt good practices to keep the code clean and maintainable:

  • Handle only the exceptions you can actually handle and let the others propagate.
  • Avoid using generic catch blocks that catch the Exception class. Prefer to catch specific types of exceptions.
  • Always clean up resources in a finally block or use the try-with-resources statement from Java 7 onwards, which automatically manages resources.
  • Use custom exceptions to represent error conditions specific to your application domain.
  • Document the exceptions that your methods can throw using the @throws tag in the Javadoc.

Exception handling is a crucial aspect of Java programming, as it allows you to create more stable and reliable applications. By understanding the structure of classes and objects in Java and how exceptions work, you will be well equipped to handle unexpected situations and keep your code running smoothly.

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 catch block is designed to handle exceptions thrown by the try block. Multiple catch blocks can be used to manage different exception types, providing tailored responses for each. The finally block runs regardless of whether an exception was thrown, and runtime exceptions like RuntimeException do not need explicit handling.

Next chapter

Encapsulation and accessor methods (getters and setters)

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