异常
抛出异常
捕获异常
异常处理的五个关键字:
try catch finally throw throws
package oop01.exception.demo02;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//监控区域
System.out.println(a/b);
} catch (Exception e) {
System.out.println("Exception");
} finally {
}
}
}
try——catch——finally
快捷键:ctrl+alt+T
package oop01.exception.demo02;
public class Test {
public static void main(String[] args) {
//Throwable -->Error
//Throwable -->Exception
//捕获多个异常 从小到大
try {//监控区域
new Test().a();
} catch (Error e) {//捕获异常
System.out.println("Error");
} catch (Exception e) {
System.out.println("Exception");
}catch (Throwable e) {
System.out.println("Throwable");
}
finally {//处理善后工作
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
结果:
Error
finally
Process finished with exit code 0
package oop01.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 (Exception e) {
System.exit(0);
e.printStackTrace();//打印栈信息
} finally {
}
}
}
throw和throws
package oop01.exception;
public class Test03 {
public static void main(String[] args) {
try {
new Test03().test(1,0);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
//假设这方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
//System.out.println(a/b);
}
}
自定义异常
- 使用java内置的异常类可以描述在编程时出现的大部分异常情况。除此之外,用户还可以自定义异常。用户自定义异常,只需要继承Exception类即可。
package oop01.exception.demo01;
public class MyException extends Exception{
//传递数字
private int detail;
public MyException(int detail) {//构造
this.detail = detail;
}
//toString
@Override
public String toString() {
return "MyException{" + "detail=" + detail + '}';
}
}
package oop01.exception.demo01;
//自定义异常
public class Test {
//可能会存在异常的方法
public 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.test(15);
} catch (MyException e) {
System.out.println("MyException=>"+e);
} finally {
}
}
}
实际应用中的经验总结
- 处理运行异常时,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面。可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,可以加try—catch
- 尽量去处理异常,不要只是简单的调用打印输出
catch (MyException e) {
System.out.println("MyException=>"+e);
- 尽量添加finally语句块去释放占用的资源