关与 重新抛出异常的问题
麻烦大家看2个小程序
一:通过方法printStackTrace(),看出重新抛出异常对象,起调用栈信息不变
package mytool;
class MyException extends Exception
{
}
class ReThrowing
{
public void f() throws MyException
{
throw new MyException();
}
public void g() throws MyException
{
try
{
f();
}
catch(MyException myE)
{
System.err.println("catch MyException from f()");
myE.printStackTrace();
throw myE;
}
}
}
public class ToTestRethrowing
{
public static void main(String[] args)
{
ReThrowing a = new ReThrowing();
try
{
a.g();
}
catch(MyException myEe)
{
System.err.println("catch MyException from g()");
myEe.printStackTrace();
}
}
}
二:通过fillInStackTrace()刷新调用栈信息
package mytool;
class MyException extends Exception
{
}
class ReThrowing
{
public void f() throws MyException
{
throw new MyException();
}
public void g() throws Throwable
{
try
{
f();
}
catch(MyException myE)
{
System.err.println("catch MyException from f()");
myE.printStackTrace();
throw myE.fillInStackTrace();
}
}
}
public class ToTestRethrowing
{
public static void main(String[] args) throws Throwable
{
ReThrowing a = new ReThrowing();
try
{
a.g();
}
catch(MyException myEe)
{
System.err.println("catch MyException from g()");
myEe.printStackTrace();
}
}
}
问题: fillInStackTrace()返回的是Trowable对象,应该将方法g()异常声明由MyException改为Trowable即可,mian()方法并不需要抛出异常(如程序一),在程序二中为什么要在main()方法上进行异常声明?