1.产生异常
package cn.mldn.demo;
public class JavaDemo {
public static void main(String args[]) {
System.out.println("【1】****** 程序开始执行 ******");
System.out.println("【2】****** 数学计算:" + (10 / 0));
System.out.println("【3】****** 程序执行完毕 ******");
}
}
2.异常的捕获与处理
package cn.mldn.demo;
public class JavaDemo {
public static void main(String args[]) {
System.out.println("【1】****** 程序开始执行 ******");
try {
System.out.println("【2】****** 数学计算:" + (10 / 0));
} catch (ArithmeticException e) {
System.out.println("【C】处理异常:" + e);
}
System.out.println("【3】****** 程序执行完毕 ******");
}
}
3.处理多个异常
package cn.mldn.demo;
public class JavaDemo {
public static void main(String args[]) {
System.out.println("【1】****** 程序开始执行 ******");
try {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
System.out.println("【2】****** 数学计算:" + (x / y)) ;
} catch (ArithmeticException e) {
e.printStackTrace() ;
} catch (NumberFormatException e) {
e.printStackTrace() ;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace() ;
} finally {
System.out.println("【F】不管是否出现异常,我都会执行。") ;
}
System.out.println("【3】****** 程序执行完毕 ******");
}
}
4.throws关键字
package cn.mldn.demo;
class MyMath {
public static int div(int x, int y) throws Exception {
return x / y;
}
}
public class JavaDemo {
public static void main(String args[]) {
try {
System.out.println(MyMath.div(10, 2));
} catch (Exception e) {
e.printStackTrace();
}
}
5.自定义异常
package cn.mldn.demo;
class BombException extends Exception {
public BombException(String msg) {
super(msg);
}
}
class Food {
public static void eat(int num) throws BombException {
if (num > 9999) {
throw new BombException("米饭吃太多了,肚子爆了。");
} else {
System.out.println("正常开始吃,不怕吃胖。");
}
}
}
public class JavaDemo {
public static void main(String args[]) {
try {
Food.eat(11);
} catch (BombException e) {
e.printStackTrace();
}
}
}