Topic: 谁来处理从main方法throws出去的Exception?

  Print this page

1.谁来处理从main方法throws出去的Exception? Copy to clipboard
Posted by: Jcat
Posted on: 2006-05-07 18:53

我们知道,如果想偷懒,可以让需要处理异常的方法(比如包含try-catch块),将异常throws出去(这样就不用写try-catch块了),但异常终归是要处理的。
那么谁来处理从main方法throws出去的Exception?机制是怎样的?

谢谢!

2.Re:谁来处理从main方法throws出去的Exception? [Re: Jcat] Copy to clipboard
Posted by: ranchgirl
Posted on: 2006-05-08 00:28

Nobody, it will throw out your consoler and stop the execution of you program.

You want to test?


public static void main(String[] args) {
throw new RuntimeException("I am a RuntimeException for Jcat to test out :), Haha");
}

3.Re:谁来处理从main方法throws出去的Exception? [Re: Jcat] Copy to clipboard
Posted by: Jcat
Posted on: 2006-05-08 12:01

谢谢,总结如下

import java.io.IOException;

public class TryCatch {
public static void main(String[] args) {
try {
throw new IOException("IOException");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} // 因为处理了异常,所以可以编译,可以运行

import java.io.IOException;

public class CheckedExceptionWithThrows {
public static void main(String[] args) throws IOException {
throw new IOException("IOException");
}
} // 只是(向上/外)抛出了异常,所以可以编译,运行时出错

import java.io.IOException;

public class CheckedExceptionWithoutThrows {
public static void main(String[] args) {
throw new IOException("IOException");
}
} // 产生了Checked异常(即非RuntimeException),并未处理,也未抛,所以编译时就出错了

public class RuntimeExceptionWithoutThrows{
public static void main(String[] args) {
throw new RuntimeException("RuntimeException");
}
} // 产生的是RuntimeException,所以不用处理或抛,仍然可以通过编译,但运行时出错

总之,有异常不处理,早(编译时)晚(运行时)要出错的。

4.Re:谁来处理从main方法throws出去的Exception? [Re: Jcat] Copy to clipboard
Posted by: ranchgirl
Posted on: 2006-05-08 14:51

Did you notice I was throwing RuntimeException?

It is another catagory...

5.Re:谁来处理从main方法throws出去的Exception? [Re: Jcat] Copy to clipboard
Posted by: uniquejava
Posted on: 2006-05-08 16:52

you don't need to handle RuntimeException,
所以例3中“只产生了异常,所以编译时就出错了”这句话不完全正确。
but you need to handle other exceptions
(in this case, we can do nothing in the catch clause or just throw it to the higher level)
谁来处理我也不清楚,JVM来处理吧。内部细节我也不知道了。:

6.Re:谁来处理从main方法throws出去的Exception? [Re: Jcat] Copy to clipboard
Posted by: cxp108
Posted on: 2006-05-08 17:14

IOException 是可以预见的异常,编译器能够预测到代码有发生该异常的可能性,因此编译器会强制要求你对这部分代码进行 try & catch 。

RuntimeException 是运行时的异常,编译器是无法预测到的,因此不会要求你进行try & catch
其实最经常出现的RuntimeException 就是NullPointerException,编译器是无法预测到这个异常会在什么时候发生,也很少有代码声明抛出这种异常。

呵呵,不知道说得对么,不对请各位指正哈 Smile

7.Re:谁来处理从main方法throws出去的Exception? [Re: Jcat] Copy to clipboard
Posted by: Jcat
Posted on: 2006-05-08 21:54

谢谢各位不吝指点,我已经修正了我的例子,并按cxp108的意思加了一个case。

如还有不对的请继续指出 Smile


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923