- try{}catch{}定义异常 和finally
package duixiang6;
public class Example21 {
public static void main(String[] args) {
try{int result =divide(4,0);
System.out.println(result);
}catch(Exception e){
System.out.println(" "+e.getMessage());
}
System.out.println("");
} public static int divide(int x,int y) {
int result=x/y;
return result;
}
}
- thorws抛异常
package duixiang6;
public class Example23 {
public static void main(String[] args) {
try{int result =divide(4,2);
System.out.println(result);
}catch(Exception e){
System.out.println(" "+e.getMessage());
}
}
public static int divide (int x,int y)throws Exception {
int result=x/y;
return result;
}
}
- 自定义异常
首先要建议异常类,继承Exception,生成有参和无参构造方法即可.(throw new 自己定义异常类(“出现异常”))