7.Java当中的异常
Uncheck exception |
class Test {
public static void main(String args[]){
System.out.println(1);
//uncheck exception运行时出异常
//有了try catch后,后面的流可以正常运行
try{
System.out.println(2);
int i=1/0;
System.out.println(3);
}
//如果出现异常,会执行catch,如果不出现异常,catch里面的代码不执行
catch(Exception e){
e.printStackTrace();
System.out.println(4);
}
System.out.println(5);
}
}
class TestCheck{
public static void main(String args[]){
//check exception必须使用try catch处理,否则编译不通过
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
System.out.println(4);
}
//finally无论如何都会执行,称为异常出口
finally{
System.out.println("finally");
}
System.out.println(5);
}
}
class User{
private int age;
public void setAge(int age) throws Exception{
//throws声明谁调用谁处理这个异常
if(age<0){
Exception e=new Exception("age is not right");
throw e;//抛出异常对象
}
this.age=age;
}
}
class Test {
public static void main(String args[]){
User user=new User();
try{
user.setAge(-20);
}
catch (Exception e){
System.out.println(e)
}
}
}