e = new ArithmeticException("test");//为什么不能对变量重新赋值
}catch(Exception e){
System.out.println("未知异常");
e = new RuntimeException("test"); //这里可以正常赋值
}
复制代码
catch (IndexOutOfBoundsException|NumberFormatException|ArithmeticException e) {
System.out.println("数组越界、格式异常、算术异常之一");
e = new ArithmeticException("test");//为什么不能对变量重新赋值
System.out.println("未知异常");
e = new RuntimeException("test"); //这里可以正常赋值
}
作者: 程振 时间: 2012-9-13 09:17
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.ArithmeticException
复制代码
你这是类型转换问题,看上面的继承结构:ArrayIndexOutOfBoundsException,ArithmeticException等等,这几个异常类是都是RuntimeException的子类,子类A赋予子类B是不对了,所以第一个catch不对。而第二个catch是把子类RuntimeException赋予父类Exception则是可以的。作者: 杨卫腾 时间: 2012-9-13 09:48
e = new ArithmeticException("test");
{
public static void main(String[] args)
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("结果为:" + c);
}
catch (IndexOutOfBoundsException|NumberFormatException|ArithmeticException e)
{
System.out.println("数组越界、格式异常、算术异常之一");
e = new ArithmeticException("test");
}
catch(Exception e)
{
System.out.println("未知异常");
e = new RuntimeException("test"); //这里可以正常赋值
}
}
}
这就相当于 class Cat extends Animal{} class Dog extends Animal{}
Cat c = new Cat();
c = new Dog(); 不兼容类型 作者: 柳彬 时间: 2012-9-13 10:08
这是因为你程序捕获的异常不是ArithmeticException异常,所以.e = new ArithmeticException("test");
错误,不管他是IndexOutOfBoundsException|NumberFormatException|ArithmeticException 中的哪个他们都
是RuntimeException的子类。所以子类是可以赋给父类的。如果捕获的事ArithmeticException时
10.e = new ArithmeticException("test");可以赋值
代码证明:
import java.lang.*;
public class DivTest2 {
public static void main(String[] args) {
try {
int a =3;
int b =0;
int c = a / b;
System.out.println("结果为:" + c);
}
catch (ArithmeticException e){
e = new ArithmeticException("test");
System.out.println("算术异常");
System.out.println(e.toString());
//为什么不能对变量重新赋值
}catch(Exception e){
System.out.println("未知异常");
e = new RuntimeException("test"); //这里可以正常赋值
System.out.println(e.toString());
}
}
}
运行结果:
算术异常
java.lang.ArithmeticException :test