我有问题。编码如下图所示。当我运行程序并输入“aaa”时,它显示错误,因为它只捕获算术异常。如何根据出现的问题添加适当的代码来克服异常?
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");
}
}
我已经找到答案了!编码如下:
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");
}
}