java基础异常处理
异常的定义:中断了正常指令流的事件。
try..catch..finally结构:
class Test{ public static void main(String[] args){ System.out.println(1); 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(5); } System.out.println(6); } }
输出结果:
D:\Java\code\练习十二>java Test
1
2
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:6)
4
5
6
throw与throws关键字
class User{
private int age;
public void setAge(int age) throws Exception{
if(age <= 0){
Exception e = new Exception("input age is error!");
throw e;
}
else{
this.age=age;
}
}
}
class Test{ public static void main(String[] args){ User u = new User(); try{ u.setAge(-20); } catch(Exception e){ System.out.println(e); } } }
D:\Java\code\练习十二>java Test java.lang.Exception: input age is error!

浙公网安备 33010602011771号