Java Reference
In-Depth Information
The finally block is used when we want to execute something at the end regardless
of whether an exception occurred or not. This can include, for example, closing a file or
freeing resources.
Next, we will present an example code that can raise multiple exceptions.
import java . util . ;
public class Test {
public static void main(String args [])
{
while ( true )
{
try {
Scanner console = new Scanner(System. in) ;
System. out . print ( "Enter a number: " );
int i=console.nextInt();
if (i % 2 == 0)
{
throw new EvenException() ;
break ;
}
catch (InputMismatchException e) {
System. out . println ( "Not a number! Try again!" );
}
catch (EvenException e) {
System. out . println ( "Number is even! Try again!" );
}
catch (Exception e) {
System. out . println ( "Something went wrong! Try again!" );
}
}
}
}
class EvenException extends Exception
{
public EvenException() {
super ( "Even number exception" );
}
}
First, note that we created our own exception class. As expected, our exception class
inherits from the Exception class. The constructor passes the name of the exception to the
Exception superclass. Next, let us examine the main method. An InputMismatchException
will be generated if an integer is not entered. Similarly, an EvenException will be generated
when an even integer is entered. The throw keyword is used to generate a new exception.
Our code has three catch statements: if the user enters something that is not an integer, if
the user enters an even number, and if something else goes wrong.
Extra care should be taken in the ordering of the catch blocks. We should always
order them from the most specific exception to the most general exception.
If catch(Exception e) was the first exception, then there is no chance that another
catch block will be executed. When an exception object is generated, Java checks the first
catch statement. If the exception object does not belong to the exception class in the first
catch statement, then Java proceeds to the next catch statement and so on. On a side
note, if the check blocks are not ordered correctly from the most specific one to the most
general one, the program will simply not compile.
 
Search WWH ::




Custom Search