public class TryCatch
{ public static void main(String args[])
{ int array[]={0,0};
int num1,num2,result=0;
num1=100;
num2=0;
try
{ result = num1/num2;
System.out.println(num1/array[2]);//更多语句
}
catch (Exception e)
{ System.out.println("Some other error: "); }
// catch (ArithmeticException e)
{ System.out.println("Error,Division by zero ") ; }
// catch (ArrayIndexOutOfBoundsException e)
{System.out.println("Error.Out of bounds"); } System.out.println("The result is:"+result);//程序继续
}
}/*输出结果
D:\>java TryCatch
Some other error:
Error,Division by zero
Error.Out of bounds
The result is:0
*/
/*去掉注释后的结果:
D:\>javac TryCatch.java
TryCatch.java:14: 已捕捉到异常 java.lang.ArithmeticException
catch (ArithmeticException e)
^
TryCatch.java:16: 已捕捉到异常 java.lang.ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e)
^
2 错误*/为什么如果注释掉子类异常程序会正常运行?但是运行结果为什么又会捕捉到两个异常呢?不是如果碰到一个异常就会停止,再搜索处理异常的Catch吗?
当子类放在父类后面时,程序不能正常编译,直接说程序异常,是不是规定子类必须放在父类后面?
{ public static void main(String args[])
{ int array[]={0,0};
int num1,num2,result=0;
num1=100;
num2=0;
try
{ result = num1/num2;
System.out.println(num1/array[2]);//更多语句
}
catch (Exception e)
{ System.out.println("Some other error: "); }
// catch (ArithmeticException e)
{ System.out.println("Error,Division by zero ") ; }
// catch (ArrayIndexOutOfBoundsException e)
{System.out.println("Error.Out of bounds"); } System.out.println("The result is:"+result);//程序继续
}
}/*输出结果
D:\>java TryCatch
Some other error:
Error,Division by zero
Error.Out of bounds
The result is:0
*/
/*去掉注释后的结果:
D:\>javac TryCatch.java
TryCatch.java:14: 已捕捉到异常 java.lang.ArithmeticException
catch (ArithmeticException e)
^
TryCatch.java:16: 已捕捉到异常 java.lang.ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e)
^
2 错误*/为什么如果注释掉子类异常程序会正常运行?但是运行结果为什么又会捕捉到两个异常呢?不是如果碰到一个异常就会停止,再搜索处理异常的Catch吗?
当子类放在父类后面时,程序不能正常编译,直接说程序异常,是不是规定子类必须放在父类后面?
public class TryCatch
{ public static void main(String args[])
{ int array[]={0,0};
int num1,num2,result=0;
num1=100;
num2=0;
try
{ result = num1/num2;
System.out.println(num1/array[2]);//更多语句
}
catch (Exception e)
{ System.out.println("Some other error: "); }
/* catch (ArithmeticException e)
{ System.out.println("Error,Division by zero ") ; }
// catch (ArrayIndexOutOfBoundsException e)
{System.out.println("Error.Out of bounds"); }
*/
System.out.println("The result is:"+result);//程序继续
}
}/*输出结果
D:\>java TryCatch
Some other error:
Error,Division by zero
Error.Out of bounds
The result is:0
*/
/*去掉注释后的结果:
D:\>javac TryCatch.java
TryCatch.java:14: 已捕捉到异常 java.lang.ArithmeticException
catch (ArithmeticException e)
^
TryCatch.java:16: 已捕捉到异常 java.lang.ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e)
^
2 错误*/当子类放在父类后面时,程序为什么不能正常编译?(请解释原因)
直接说程序异常,是不是规定子类必须放在父类前面?
上面的程序写错了,不好意思。
一般先写上特殊情况(子),最后写一般情况(父)
to 3楼,你的思路好象不对,不管怎么样都不会捕捉到数组越界的异常。请求大家再细心帮我看下程序,务必看注释的内容。
PS:
Error,Division by zero
Error.Out of bounds
第一个注释的输出内容中,这两句应该去掉。