Transcripted Summary

If your method has code that has the potential of throwing an exception, you must either catch that exception or rethrow it.


# Rethrowing Exceptions

When a method throws an exception, it is assumed that the exception will be caught and handled, or rethrown by any calling methods.

Let's look at an example where we're going to write a program that creates a new file but does not catch the exceptions.



Let's make a new method and called createNewFileRethrow.

And inside of here, instead of doing try/catch we can say, "Listen, I know that this might throw an exception, but I don't want to handle that exception. I would like to just rethrow the exception."

You can do this by adding the throws word to the methods header, and then specifying the Exception that will be thrown.

package chapter13;

public class ExceptionHandling {

    public static void main(String args[]){
        createNewFileRethrow();
    }

    public static void createNewFileRethrow() throws IOException{
        File file = new File("resources/nonexistent.txt");
        file.createNewFile();
    }
}

So, we know that this one throws an IOException, so we'll put IOException.

Polymorphism also works here, so you could say just Exception if you didn't know exactly what exceptions might be thrown. Now, if any method calls this method, then they are now on the hook for handling the exception.

If we add this createNewFileRethrow() to the main() method, we see an error because we didn't handle it.



So, again, we can fix this by placing this within a try/catch block or by adding throws IOException to the main() method.


# Throwing Exceptions

Your method can initiate the throwing of an exception by using the word throw inside of the method's body and instantiating an exception.

Notice here, this method accepts hours and rate, but perhaps you don't allow overtime.



There's no Java exception that will be automatically called for such a thing, as this is only an error from the programmer's perspective.

So, the programmer themselves can throw an exception.

They can throw one that already exists, like this IllegalArgumentException, and just pass in a custom error message.

Or they can even define their own custom exception class, which extends from Exception. And they can throw that instead. Perhaps something like NoOvertimeAllowedException.



Optional Independent Exercise

Your optional exercise for this chapter is to write the following statement — int c = 30/0 — within a program and execute it.



When you execute this, you'll see an exception, so I want you to update that program to handle the exception.

Then print a statement after the division to say, "Division is fun." This statement should be outputted no matter what happens in your program.

Good luck.

Solution

Programming can be done many different ways, but here’s my solution.



Resources



© 2024 Applitools. All rights reserved. Terms and Conditions Privacy Policy GDPR