try-catch

今天写了一个代码,改正了我一个错误。
最开始我的以为是try-catch块,如果进入catch块,那么剩下的所有代码都不能运行了,今天写了一个代码改正了自己的错误。

public class MyExceptionTest {

public static void f() throws MyException{
System.out.println("Throwing MyException from f()");
throw new MyException();
}
public static void g() throws MyException{
System.out.println("Throwing MyException from g()");
throw new MyException("originated in g()");
}
public static void main(String[] args) {
try{
f();
}catch(MyException e){
e.printStackTrace();
}
try{
g();
}catch(MyException e){
e.printStackTrace();
}
}
}
class MyException extends Exception{
private static final long serialVersionUID = 3461899582505930473L;
public MyException(){}
public MyException(String msg){
super(msg);
}

}
其实catch抓到了就不会影响catch块下面正常的代码。只是不让try快下面的代码不执行了,如果想不让所有剩下的都不运行,那么就throw new 个异常

猜你喜欢

转载自skywhsq1987.iteye.com/blog/1476306