由java虚拟机(JVM)生成并抛出,如:
一般由程序逻辑错有引起,可以尽量避免
有一个重要的子类:RuntimeException(运行时异常):
区别:
抛出异常
捕获异常
关键字:try catch finally throw throws
package com.exception;
public class TextException {
static int a = 1;
static int b = 0;
public static void main(String[] args) {
test_1();
test_2();
test_3();
test_4();
}
// 捕获单个异常
public static void test_1() {
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("出现捕获ArithmeticException异常");
} finally { // 不管有没有异常,这里都执行
System.out.println("我也不知道有没有异常");
}
}
// 捕获多个异常 Throwable > Error、Exception > other
public static void test_2() {
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("出现捕获ArithmeticException异常");
} catch (Exception e) {
System.out.println("出现捕获Exception异常");
} catch (Throwable e) {
e.printStackTrace(); // 打印错误的栈信息
} finally {
System.out.println("我也不知道有没有异常");
}
}
public static void test_3() {
if (b==0){
throw new ArithmeticException(); // 主动抛出异常
}
}
public static void test_4() throws ArithmeticException{
}
}
package com.exception;
public class MyException extends Exception {
private int detail;
public MyException(int a) {
this.detail = a;
}
@Override
public String toString() { // 异常的打印信息
return "MyException{" + "detail=" + detail + ‘}‘;
}
}
class Text {
public static void getException(int a) throws MyException {
if(a>10){
throw new MyException(a);
}
System.out.println("正常");
}
}
class run{
public static void main(String[] args) throws MyException {
new Text().getException(11);
}
}
原文:https://www.cnblogs.com/bigllxx/p/15135533.html