我有問題。編碼如下所示。當我運行程序並輸入「aaa」時,它顯示錯誤,因爲它只捕獲算術異常。如何添加適當的代碼來克服基於問題發生的異常?程序趕上算術異常,並且將展示finally塊
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");
}
}
什麼碼例外......? –
您忘記了粘貼代碼。點擊[編輯],並添加它。 – dasblinkenlight
您是否介意加入你的源代碼?謝謝。 – reporter