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)
}
}
}