你不想捕获的话就throw,如果方法中有要throw异常,就在声明方法的时候写上throws 异常。 比如 public static int parseInt(String s, int radix) throws NumberFormatException { if (s == null) { throw new NumberFormatException("null"); } if (radix < Character.MIN_RADIX) { throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); } if (radix > Character.MAX_RADIX) { throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX"); }在方法定义中写throws,在方法内部用throw庖厨异常。 这样调用方法的时候捕获就可以了。
楼主【Rush_2008】截止到2008-07-27 16:24:08的历史汇总数据(不包括此帖):
发帖的总数量:9 发帖的总分数:105 每贴平均分数:11
回帖的总数量:42 得分贴总数量:10 回帖的得分率:23%
结贴的总数量:9 结贴的总分数:105
无满意结贴数:2 无满意结贴分:30
未结的帖子数:0 未结的总分数:0
结贴的百分比:100.00% 结分的百分比:100.00%
无满意结贴率:22.22 % 无满意结分率:28.57 %
敬礼!
比如 public static int parseInt(String s, int radix) throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
} if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
} if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}在方法定义中写throws,在方法内部用throw庖厨异常。
这样调用方法的时候捕获就可以了。
throws Exception只是一种偷懒的做法。
int num = int.parse(str);字符串转为int类型的时候,我用try catch
String str = "1234";
int num;
try {
num = Integer.parseInt(str);
} catch (NumberFormatException numberFormatException) {
numberFormatException.printStackTrace();
}
而是在调用A方法的B方法中处理
那么A方法就throw异常
B方法try catch
}
catch(Exception e){
//异常处理
}
用try-catch可以捕获。 这样可以对程序产生的异常进行处理。
如果不想处理异常,可以用throws Exception抛出异常。
理解"捕获"与"抛出"就自然明白了!
但如果我写的程序代码是给别的程序员调用的,这个在大的项目中经常会出现的
那我就应该用throws,告诉那个程序员,这边可能会出错哦,你给处理一下吧.就这样