I have problem. The coding is shown as below. When I run the program and enter “aaa”, it shows error because it only catch arithmetic exception. How to add an appropriate codes to overcome the exception based on the problem occur?
import java.io.* ;
public class FinallyPractice1
{
public static void main(String [])
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String inData; int num=0, div=0;
try
{ System.out.println("Enter the numerator:");
inData=stdin.readLine();
num=Integer.parseInt(inData);
System.out.println("Enter the divisor:");
inData=stdin.readLine();
div=Integer.parseInt(inData);
System.out.println(num+"/"+div+" is "+(num/div));
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("You can't divide "+ num + " by " + div);
}
catch(ArithmeticException aex)
{
System.out.println("You entered not a number: " + inData);
}
finally
{
System.out.println("If the division didn't work, you entered bad data.");
}
System.out.println("Good-by");
}
}

I already find the answers! The coding is like below:
import java.io.* ;
public class FinallyPractice1
{
public static void main(String [] a) throws IOException
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String inData; int num=0, div=0;
try
{ System.out.println("Enter the numerator:");
inData=stdin.readLine();
div=Integer.parseInt(inData);
System.out.println("Enter the divisor:");
inData=stdin.readLine();
div=Integer.parseInt(inData);
System.out.println(num+"/"+div+" is "+(num/div));
}
catch(ArithmeticException ae)
{
System.out.println("ArithmeticException by " + div);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("You can't divide "+ num + " by " + div);
}
catch(NumberFormatException ae)
{
System.out.println("NumberException");
}
finally
{
System.out.println("If the division didn't work, you entered bad data.");
}
System.out.println("Good-by");
}
}
As you are deliberately inputting bad data “aaa”, your statement:
will throw a
NumberFormatException. You could add a catch block for this: