EXCEPTIONS IN JAVA
USE THE KEYWORD THROWS
If we do not handle a certain group of exceptions in the code, it may happen that the program ends with an error message. If a method has the potential to generate exceptions, those using that method need to know this so that they can take their own countermeasures. Let’s look at how to declare a method with the throws keyword.
exc-list are the exception classes that the method is unable or unwilling to handle. The classes excluded from this mechanism are those whose superclass is Error and RuntimeException.
Error are exceptions that we are unable to handle, such as a network error. In all other cases we must necessarily state that there is a possibility of generating exceptions.
Now those who invoke myMethod() can use two strategies, the first is to handle the exception. See the figure.
Or it can again raise the exception, this chain can go all the way to the main method.
THE CODE BLOCK FINALLY
Let’s go back and look at the code example from the previous article.
We can introduce in the try/catch block an additional block of code that is always executed. The block is finally.
The use normally made of finally is to, for example, close a file, a connection to a database etc.
RAISE AN EXCEPTION
Using our usual example, let’s see how an exception is raised.
Program execution stops exactly where the instance of ArithmeticException() is created, and it begins to traverse the call stack to find an error handler for division by zero if one exists, otherwise the program terminates abnormally. If you want to raise an exception as well, let’s see how to do it. Look at the figure.
With the throw e the exception is no longer removed but is thrown again. The reason for doing this is to look for a higher-level method that further handles the propagated exception, or because after handling the error in the catch block we want to prematurely terminate the program.
CREATE AN EXCEPTION CLASS
We will learn how to create a new class that represents our exception. Let’s look at a trivial example. The println method will print “
Custom Exception!“. The toString() method of the Object class is redefined instead of a throwable class method.
LINKS TO PREVIOUS POSTS
LINK TO CODE ON GITHUB
EXECUTION OF THE EXAMPLE CODE
- Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.
java -jar –enable-preview CorsoJava.jar
- Or run the main found in the file CorsoJava.java.
Leave A Comment