1.异常
一、Error和Exception
package org.psmaxwell.exception;
//Exception in thread "main" java.lang.StackOverflowError
public class Demo01 {
public static void main(String[] args) {
new Demo01().a();
}
public void a(){
b();
}
public void b(){
a();
}
}
package org.psmaxwell.exception;
public class Demo01 {
public static void main(String[] args) {
//Exception in thread "main" java.lang.ArithmeticException: / by zero
System.out.println(11/0);
}
}
要理解Java异常处理是如何工作的,你需要掌握以下三种类型的异常:
1.检查性异常:最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。
2.运行时异常:运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
3.错误ERROR:错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。
异常体系结构
ERROR
Exception
二、 捕获和抛出异常
异常处理五个关键字:
try、catch、finally、throw 、throws
package org.psmaxwell.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常,从小到大!
try { //try监控区域
System.out.println(a/b);
} catch (Error e) { //catch(想要捕获的异常类型) 捕获异常
System.out.println("Error");
} catch (Exception e) {
System.out.println("Exception");
}catch (Throwable e) {
System.out.println("Throwable");
} finally { // 处理善后工作
System.out.println("finally");
}
//finally 可以不要 finally,假设IO 资源关闭
}
}
package org.psmaxwell.exception;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// CTRL + ALT + T
try {
System.out.println(a/b);
} catch (java.lang.Exception e) {
e.printStackTrace(); // 打印错误栈信息
} finally {
}
}
}
package org.psmaxwell.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
//假设这个方法中,处理不了这个异常,方法上抛出异常。
public void test(int a,int b){
if (b==0){
throw new ArithmeticException(); // 主动抛出异常,一般在方法中使用。
}
System.out.println(a/b);
}
}
/**
* //假设要捕获多个异常,从小到大!
*
* try { //try监控区域
*
* if (b==0){
* throw new ArithmeticException(); //主动抛出异常
* }
* System.out.println(a/b);
*
* } catch (Error e) { //catch(想要捕获的异常类型) 捕获异常
* System.out.println("Error");
* } catch (Exception e) {
* System.out.println("Exception");
* }catch (Throwable e) {
* System.out.println("Throwable");
* } finally { // 处理善后工作
* System.out.println("finally");
* }
*/