EXCEPTIONS IN JAVA

USE THE KEYWORD THROWS

java-logo

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.

Throws

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 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.

IOException

Now those who invoke myMethod() can use two strategies, the first is to handle the exception. See the figure.

Eccezione gestita

Or it can again raise the exception, this chain can go all the way to the main method.

Sollevare nuovamente una eccezione

THE CODE BLOCK FINALLY

Let’s go back and look at the code example from the previous article.

Division by zero

We can introduce in the try/catch block an additional block of code that is always executed. The block is finally.

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.

Lanciare una eccezione

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.

Rilanciare una eccezione

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.

Eccezione personalizzata

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

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.