abnormal
1 Overview
- An exception is that the program appeared in unusual circumstances
2. Architecture
3. JVM the default way to handle exceptions
- The output unusual name, location and cause of the error exception occurs in the console
- Program to stop execution
4. try-catch manner exception
① Definition Format
try {
可能出现异常的代码;
} catch(异常类名 变量名) {
异常的处理代码;
}
② execution process
- Program starts executing code from a try inside
- If an exception occurs, it will jump to the corresponding catch inside to perform
- After execution is completed, the program can continue down
Example ③
public class ExceptionDemo01 {
public static void main(String[] args) {
System.out.println("开始"); // 输出开始
method();// 方法中存在异常, 但并不会终止程序
System.out.println("结束"); // 输出结束
}
public static void method() {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[3]); // 索引越界异常,程序跳转到catch中
System.out.println("这里能够访问到吗");// 该条代码不会执行
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace(); // 输出异常信息
}
}
}
5. throws exception manner
① Definition Format
public void 方法() throws 异常类名 {
}
② example
public class ExceptionDemo {
public static void main(String[] args) {
System.out.println("开始");
// method();
try {
method2();
}catch (ParseException e) {
e.printStackTrace();
}
System.out.println("结束");
}
//编译时异常
public static void method2() throws ParseException {
String s = "2048-08-09";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(s);
System.out.println(d);
}
//运行时异常
public static void method() throws ArrayIndexOutOfBoundsException {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
}
}
The difference between abnormal and abnormal operation 6. compile time
① compile-time anomaly
- Exception class and its subclasses are
- Must display processing, otherwise the program will error, not compile
② runtime exception
- It is RuntimeException and its subclasses
- Without displaying processing, can also be treated as an exception and compile-time
7. custom exception
// 自定义异常类
class ScoreException extends Exception {
public ScoreException() {}
public ScoreException(String message) {
super(message);
}
}
// 老师类
class Teacher {
public void checkScore(int score) throws ScoreException {
if(score<0 || score>100) {
// throw new ScoreException();
throw new ScoreException("你给的分数有误,分数应该在0-100之间");
} else {
System.out.println("成绩正常");
}
}
}
// 测试类
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入分数:");
int score = sc.nextInt();
Teacher t = new Teacher();
try {
t.checkScore(score);
} catch (ScoreException e) {
e.printStackTrace();
}
}
}