一、网课截图
1.1 Error和Exception
1.2 捕获和抛出异常
package exception;
/**
* Author: Gu Jiakai
* Date: 2021/7/28 6:50
* FileName: Demo01
* Description:
*/
public class Demo01 {
public static void main(String[] args) {
// 假设要捕获多个异常:从小到大!
int a = 1;
int b = 0;
try {
new Demo01().test(a,b);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
}
//
// try {//try监控区域
//
//
// } 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可以不要,假设IO,资源,关闭!
}
// 假设这方法中,处理不了这个异常,方法上抛出异常。
public void test(int a,int b) throws ArithmeticException{
if(b==0){//主动抛出异常 throw throws
throw new ArithmeticException();//一般在方法中使用
}
// System.out.println(a / b);
}
}
package exception;
/**
* Author: Gu Jiakai
* Date: 2021/7/28 7:04
* FileName: Demo02
* Description:
*/
public class Demo02 {
public static void main(String[] args) {
int a=1;
int b=0;
// ctrl+alt+t
try {
System.out.println(a/b);
} catch (Exception e) {
// System.exit(0);
e.printStackTrace();//打印错误的栈信息。
} finally {
}
}
}
1.3 自定义异常
IDEA查看源码快捷键:鼠标中键。
IDEA搜索快捷键:连续按两次shift。
IDEA构造函数快捷键:alt+insert
IDEA万能快捷键:alt+enter
package exception;
/**
* Author: Gu Jiakai
* Date: 2021/7/28 7:17
* FileName: MyException
* Description:
*/
//自定义的异常类。
public class MyException extends Exception {
//传递数字>10
private int detail;
public MyException(int detail) {
this.detail = detail;
}
// toString:异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
package exception;
/**
* Author: Gu Jiakai
* Date: 2021/7/28 7:30
* FileName: Test
* Description:
*/
public class Test {
//可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为:"+a);
if(a>10){
throw new MyException(a);//抛出。
}else {
System.out.println("ok");
}
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
// 增加一些处理异常的代码。
System.out.println("MyException->"+e);
}
}
}
//传递的参数为:11
//MyException->MyException{detail=11}