1、Error 和 Exception
以下内容均来自【狂神说Java】Java零基础学习视频通俗易懂P77
2、捕获和抛出异常
以下内容均来自【狂神说Java】Java零基础学习视频通俗易懂P78
Test 类
package com.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这个方法中,处理不了这个异常。方法上 抛出异常
public void test(int a ,int b) throws ArithmeticException{
if (b == 0) { //主动的抛出异常 throw throws ,一般用在方法中使用
throw new ArithmeticException();
}
System.out.println(a / b);
}
}
/*
//假设要捕获多个异常:从小到大
try { //监控区域
System.out.println("a/b")
}catch (Error e) { //catch 捕获异常
System.out.println("Error");
}catch (Exception e) { //catch 捕获异常
System.out.println("Exception");
}catch (Throwable e){ //catch 捕获异常
System.out.println("Throwable");
}finally { //处理善后工作
System.out.println("finally");
}
//finally 可以不要finally, 以后得IO流,资源相关得东西,得关闭
*/
Test1 类
package com.exception;
public class Test1 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// Ctrl + Alt + T
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace(); //打印错误的栈信息
}finally {
}
}
}
3、自定义异常及经验小结
以下内容均来自【狂神说Java】Java零基础学习视频通俗易懂P79
MyException 类
package com.exception.demo02;
//自定义的异常类
public class MyException extends Exception {
//传递数字 > 10 抛出异常
private int detail;
public MyException(int a){
this.detail = a;
}
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
Test 类
package com.exception.demo02;
public class Test {
//可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为: "+a);
if (a>10){
throw new MyException(a); //抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(1);
}catch(MyException e){
System.out.println("MyException=>"+e);
}
}
}