java第六天--异常

Java当中的异常

 

什么是异常?

异常:是一个由虚拟机产生的对象,中断了正常指令流的事件;(异常是运行时产生的,和编译没有关系)。

异常的分类


(RuntimeException及其子类都是uncheck的异常)

 

class Test{

public static void main(String args[]){

System.out.println(1);

//uncheek exception

//将有可能有异常的代码放在try中,一旦有异常就跳到catch中;而且不会影响后面的代码执行.finally中的代码都会运行,不管有没有异常

try{

System.out.println(2);

int i = 1/0;

System.out.println(3);

}

catch(Exception e){

e.printStackTrace();

System.out.println(4);

}

finally{

System.out.println("finally");

}

System.out.println(5);

}

}

 

class TestCheck{

public static void main(String args[]){

//check exception

try{

Thread.sleep(1000);

}

catch(Exception e){

e.printStackTrace();

}

}

}

 

 

 

自定义异常:语法上没有问题,但是不符合实际,例如定义 ageint型,age可以为负数,但是实际上年龄是不能为负数的,这时可以自定义异常。使用throwthrows关键字

class User{

int age;

void setage(int age){

if(age < 0){

RuntimeException e = new RuntimeException("年龄不能为负数");

throw e;

}

this.age = age;

}

}

 

class Test{

public static void main(String args[]){

User user = new User();

user.setage(-20);

}

}

以上为uncheck的异常

 

 

若改为下面的代码:

class User{

int age;

void setage(int age) throws Exception{

if(age < 0){

Exception e = new Exception("年龄不能为负数");

throw e;

}

this.age = age;

}

}这时check exception,必须进行try...catch处理。可以使用throws,在调用这个函数的地方处理异常。

class Test{

public static void main(String args[]){

User user = new User();

try{

user.setage(-20);

}

catch(Exception e){

System.out.println(e);

}

}

}

此时运行时将产生异常。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值