public class Exception_StackOverflowError {
public static void main(String[] args) {
new Exception_StackOverflowError().a(); //StackOverflowError
}
public void a(){
b();
}
public void b(){
a();
}
}
public class Exception_ArithmeticException {
public static void main(String[] args) {
System.out.println(11 / 0); //ArithmeticException: / by zero
}
}
java.lang.Throwable
作为所有异常的超类。Error 类对象由 Java 虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关。
Java 虚拟机运行错误( VirtualMachineError ),当 JVM 不再有继续执行操作所需的内存资源时,将出现 OutOfMemoryError 。这些异常发生时, Java 虚拟机( JVM )一般会选择线程终止。
还有发生在虚拟机试图执行应用时,如类定义错误( NoClassDefFoundError )、链接错误( LinkageError )。这些错误是不可查的,因为它们在应用程序的控制和处理能力之外,而且绝大多数是程序运行时不允许出现的状况。
在 Exception 分支中有一个重要的子类 RuntimeException (运行时异常)
除了运行时异常之外的所有东西,都可以统称为非运行时异常
这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生。(异常是必须要处理的,如果不处理的话,程序有可能编译就不通过,如果程序编译都不通过,就没办法运行了)
Error 和 Exception 的区别: Error 通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时, Java 虚拟机一般会选择终止线程; Exception 通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常。
捕获异常
如果不用 try - catch ,遇到错误程序就直接停止了,但是用了 try - catch 去捕获之后,程序会依旧正常的往下执行
finally可以不要,finally一般用来处理资源关闭
public class TryCatchFinally {
public static void main(String[] args) {
int a = 1;
int b = 0;
//捕获异常,并返回一些信息
try { //try,监控区域
System.out.println(a / b);
} catch (ArithmeticException e) { //catch,捕获异常
System.out.println("除数不能为0");
e.printStackTrace(); //打印错误的栈信息
} catch (Exception e) { //catch,捕获多个异常,层层递进,从小到大,上面捕获之后就不会执行下面的捕获了
System.out.println("程序异常");
} finally { //finally,处理善后工作
System.out.println("关闭资源");
}
System.out.println();
try { //try,监控区域
new TryCatchFinally().a();
} catch (Throwable e) { //catch(想要捕获的异常类型),捕获异常
System.out.println("栈溢出");
} finally { //finally,处理善后工作
System.out.println("关闭资源");
}
System.out.println();
//正常处理报异常,ArithmeticException: / by zero
System.out.println(a / b);
}
public void a(){
b();
}
public void b(){
a();
}
}
public class TryCatchFinally {
public static void main(String[] args) {
try {
new TryCatchFinally().test(1, 0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
System.out.println();
new TryCatchFinally().test(1, 0);
}
//假设这个方法中,处理不了这个异常,在方法上抛出异常 throws
public void test(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException(); //主动的抛出异常,一般在方法中使用 throw
}
}
}
异常处理五个关键字:
IDEA 快捷键: ctrl + alt + t
public class CustomException {
public static void main(String[] args) {
//传递数字, > 10 抛出异常
try {
test(11);
} catch (MyException e) {
//增加一些处理异常的代码
System.out.println(e);
}
}
//可能会存在异常的方法
public static void test(int i) throws MyException {
if (i > 10) {
throw new MyException(i); //抛出
}
System.out.println("ok");
}
}
//自定义的异常类
class MyException extends Exception {
private int detail;
public MyException(int detail) {
this.detail = detail;
}
//toSting:异常的打印信息
@Override
public String toString() {
return "MyException{" + "detail=" + detail + ‘}‘;
}
}
catch(Exception e){}
来处理可能会被遗漏的异常 printStackTrace();
去打印输出原文:https://www.cnblogs.com/lemon-lime/p/15086800.html