java 异常
创建场景
int a = 0;
int b = 0;
int s = b / a;
System.out.println(s);
我们的指令 自身不合理,所以java停止执行,后面的语句无法继续执行。
异常的继承关系
Exception
-
ZeroDevisionException
-
字典里面没有元素
-
NullPointer
各种类型的异常
异常的捕获
对于某些错误,我们不希望程序彻底退出
Scanner sc = new Scanner(System.in);
System.out.print("Please input 摄氏度:");
String in = sc.nextLine();
while (!in.startsWith("q")) {
int i = 0;
try {
i = Integer.parseInt(in);
}catch (NumberFormatException e) { // 匹配上,说明这种异常我们是有 预案的。。。就没必要结束了
System.out.println("您的输入不合法,请输入合法的整数");
System.out.print("Please input 摄氏度:");
in = sc.nextLine();
continue;
}
double f_ = 9.0 * i / 5.0 +32;
System.out.println("F is " + f_);
System.out.println("Please input 摄氏度:");
in = sc.nextLine();
}
多种exception的情况
int a = 0;
int b = 0;
int s = b / a;
System.out.println(s);
Scanner sc = new Scanner(System.in);
System.out.println("Please input 摄氏度:");
String in = sc.nextLine();
while (!in.startsWith("q")) {
int i = 0;
try {
i = Integer.parseInt(in);
}catch (NumberFormatException | IndexOutOfBoundsException e) {
System.out.println("您的输入不合法,请输入合法的整数");
System.out.println("Please input 摄氏度:");
in = sc.nextLine();
continue;
} catch (Exception e) {
}
double f_ = 9.0 * i / 5.0 +32;
System.out.println("F is " + f_);
System.out.println("Please input 摄氏度:");
in = sc.nextLine();
}
自定义异常
public static void register(String s) throws InvalidPhoneException {
for (int i = 0; i < s.length(); i ++) {
char ch = s.charAt(i);
if (ch < '0' || ch > '9') {
throw new InvalidPhoneException();
}
}
return ;
}
多级调用的异常
public static void level_1() {
System.out.println("start 111");
level_2();
System.out.println("end 111");
}
public static void level_2() {
System.out.println("start 222");
level_3();
System.out.println("end 222");
}
public static void level_3() {
System.out.println("start 333");
int[] arr = new int[2];
int mynum = 3;
mynum --;
for (int i = 0; i <= mynum ; i ++) {
arr[i] = i;
}
System.out.println("end 333");
}