Is an ArithmeticException a checked exception?
No.
Here is an example program.
methodA has two
try/catch structures.
The first uses the static method parseInt() of class Integer
to convert a string of characters into a primitive int.
If the string can't be converted, parseInt() throws a
NumberFormatException.
The second try/catch structure calls methodB,
which might throw an ArithmeticException.
If that happens, the second catch{} will
handle it.
The clause throws ArithmeticException in the header of methodB()
is not required, because ArithmeticExceptions are not
checked.
import java.lang.* ;
import java.io.* ;
public class BuckPasser
{
public static int methodB( int divisor ) throws ArithmeticException
{
int result = 12 / divisor; // may throw an ArithmeticException
return result;
}
public static void methodA( String input )
{
int value = 0;
try
{
value = Integer.parseInt( input ); // Convert the string to an int.
// May throw a NumberFormatException
}
catch ( NumberFormatException badData )
{
System.out.println( "Bad Input Data!!" );
return; // this is necessary; without it control will continue with the next try.
}
try
{
System.out.println( "Result is: " + methodB( value ) );
}
catch ( ArithmeticException zeroDiv )
{
System.out.println( "Division by zero!!" );
}
}
public static void main ( String[] a )
{
Scanner scan = new Scanner( System.in );
String inData;
System.out.print("Enter the divisor: ");
inData = scan.next(); // Read a string from standard input
methodA( inData ); // send the string to methodA
}
}
Here is what happens when the user enters 0 for a divisor:
Now say that the user enters the string "Rats". What message will be printed?