Learn Java Easy. Chapter 12. Try & Catch

Chapter 12. Try & Catch

Chapter 12. Try & Catch

Bud has obtained the keys he needed from Vincente’s office. They will prove essential to execute the plan. Getting out of prison won’t be easy, but returning without anyone noticing will be even more complicated.

It seems that one of the officials working at the prison hospital has been stealing some medications to sell them among the inmates. The idea is to extort him to help us get back in. It shouldn’t be too difficult; he’ll surely cooperate without problems.

Once outside, when it’s time to return, I’ll hide in the trunk of his car and simply enter until we reach the employee parking lot. From there, accessing the library without being seen is very simple. I’ll have to hide until the daily library visit time arrives and then blend in with the group.

The guard in question is named Phil and won’t help us without reason. In fact, if he finds out about our escape plans, he would immediately report us.

We need evidence of his wrongdoing; once we have it, he’ll have no choice but to cooperate. Bud will take care of that. He has many resources and seems to have been closely following Phil’s activities. For now, I don’t have to do anything, although I’ve already been warned that my contribution will be crucial at the end of the escape.

We already have an approximate date for the final phase of our plan. In two weeks there will be some holidays, and security measures usually decrease. Not much, but at least that gives us some advantage. With this information, I can now coordinate with Chani’s cousin and tell him roughly what day I’m going to leave.

Once this date range is specified, I hope Chani will take care of contacting Rich and arranging a meeting. I don’t know how we’re going to get the confession; I suppose the idea is to record audio with the mobile phone, but since I’m practically cut off from communication, I don’t have more details yet.

Introduction and importance of try and catch blocks in Java

In Java, try and catch code blocks are used to handle exceptions. Exceptions are situations that can occur while a program is running and could interrupt the normal flow of program execution. Therefore, to avoid this, we must consider these possible events and control them in advance.

These blocks are absolutely necessary since they are an organized and controlled way of dealing with errors and exceptions during program execution. Thanks to try and catch, we will avoid possible errors in our program that we don’t even account for.

The most typical exceptions

Division by Zero: By wrapping the division inside a try block, you can catch the ArithmeticException and display an appropriate error message.

String to Number Conversion: Use try-catch to catch NumberFormatException and handle invalid inputs.

Array Index Access: Protect array element access with try-catch to catch ArrayIndexOutOfBoundsException.

Safe Arithmetic Operations: Use Math.subtractExact inside a try block to catch ArithmeticException in case of overflow.

String Concatenation: Wrap the concatenation loop in a try block to catch OutOfMemoryError and handle the error.

Structure of try-catch blocks

–      Try block

try {

     // Code that may generate an exception

}

–      Catch block

It is placed directly after the try block and has this structure:

catch (ExceptionType e) {

         // Code to handle the exception

}

–      Basic example

public class Main {

    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This throws ArithmeticException
            System.out.println("The result is: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero.");
        }
    }
}

Multiple Catch Blocks

You can have multiple catch blocks to handle different types of exceptions. Each catch handles a specific exception.

public class Main {

    public static void main(String[] args) {
        try {
            // Code that may throw different exceptions
            int result = 10 / 2;
            String text = null;
            System.out.println(text.length()); // This throws NullPointerException
        } catch (ArithmeticException e) {
            // Handle ArithmeticException
            System.out.println("Arithmetic error: " + e.getMessage());
        } catch (NullPointerException e) {
            // Handle NullPointerException
            System.out.println("Error: Attempted to use a null reference.");
        }
    }
}

The finally block (Optional): You can add a finally block after the catch blocks. The finally block always executes, regardless of whether an exception was thrown or not, and is useful for releasing resources such as closing files or database connections.

public class Main {

    public static void main(String[] args) {
        try {
            // Code that may throw exceptions
            int result = 10 / 0; // This will throw ArithmeticException
            System.out.println("Result: " + result);
        } catch (Exception e) {
            // Handle any exception
            System.out.println("An exception has occurred: " + e.getMessage());
        } finally {
            // Code that always executes, with or without exception
            System.out.println("Finally block executed.");
        }
    }
}

Summary of what we’ve learned

As I mentioned at the beginning of the topic, in Java, try and catch blocks are fundamental for managing unexpected situations during program execution, avoiding interruptions in its normal development.

In simple exercises, it may not be necessary to use this structure, but when programs become more complex, it’s necessary to consider all possible events that can occur during our code execution. These blocks allow handling, among other things, errors such as division by zero, incorrect string conversions, out-of-range array accesses, and arithmetic operations that could exceed limits.

At this point, the try-catch structure shouldn’t seem very complicated. Inside the try block, we find the code that could generate an exception. If this occurs, that’s when the catch block comes into action and takes care of handling the error. You can have multiple catch blocks for different types of exceptions and optionally use the finally block to execute code that should always run, such as resource release.

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏