16.JAVA中的Exception

[size=large]Java提供了两类主要的异常:
runtime exception和checked exception。

所有的checked exception是从java.lang.Exception类衍生出来的,
而runtime exception则是从java.lang.RuntimeException或java.lang.Error类衍生出来的。

* Runtime exceptions:
  在定义方法时不需要声明会抛出runtime exception;
  在调用这个方法时不需要捕获这个runtime exception;
  runtime exception是从java.lang.RuntimeException或java.lang.Error类衍生出来的。

* Checked exceptions:
  定义方法时必须声明所有可能会抛出的checked exception;
  在调用这个方法时,必须捕获它的checked exception,不然就得把它的exception传递下去;



throw 是手动抛出异常,throw new **Exception(); 抛出的是某一个异常类型的实例.
throws 是方法抛出异常,写在方法声明处 public void show()throws **Exception,**Exception{} 紧跟throws后的是异常类型,而非异常实例,且可以声明抛出多个异常,同时这些异常类型大多都为 受检查异常类型。
throws 就是把异常抛出,就是逐级往上一级抛,但是在以后有个catch接受.
Throws抛出异常交给调用该方法的方法 处理,即:
[/size]


public class Test{
public static void main(String[] args){
Test2 test2 = new Test2();
try{
System.out.println("invoke the method begin!");
test2.method();
System.out.println("invoke the method end!");
}catch(Exception e){
System.out.println("catch Exception!");
}
}
}

class Test2{
public void method() throws Exception{
System.out.println("method begin!");
int a = 10;
int b = 0;
int c = a/b;
System.out.println("method end!");
}
}

invoke the method begin!
method begin!
catch Exception!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值