package com.msc.high;
public class ExceptionDemo {
public static void main(String[] args) {
System.out.println("--------------begin1----------------");
try {
System.out.println("10/0 = " + 10/0);
}catch (ArithmeticException e){
System.out.println(e);
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
} finally{
System.out.println("执行finally");
}
System.out.println("--------------end1----------------");
System.out.println("--------------begin2----------------");
try {
System.out.println("10/0 = " + 10+2);
}catch (ArithmeticException e){
System.out.println(e);
e.printStackTrace();
}finally {
System.out.println("执行finally");
}
System.out.println("--------------end2----------------");
}
}
输出
throw 抛出异常
package com.msc.high;
class MyMath{
public static int div(int x,int y) throws Exception{
return x/y ;
}
}
public class ExceptionDemo {
public static void main(String[] args) { //throws Exception
try {
MyMath.div(10,0) ;
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.msc.high;
class MyMath{
public static int div(int x,int y) throws Exception{
int temp = 0 ;
System.out.println("------start--------");
try{
temp = x / y ;
}catch (Exception e){
throw e ; //没有这一句 主方法输出为0 没有异常
}finally {
System.out.println("----end--------");
}
return temp ;
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
System.out.println(MyMath.div(10,0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
自定义异常
package com.msc.high;
class MyException extends Exception{
public MyException(String msg){
super("msg") ;
}
}
class Haha{
public static void print(int num) throws Exception{
if(num > 10) throw new MyException("大于10") ;
else System.out.println("小于10");
}
}
public class ExceptionDemo {
public static void main(String[] args) throws Exception {
Haha.print(1);
}
}
断言