抛出异常
捕获异常
异常的五个关键字
public static void main(String[] args) {
int a=1;
int b=0;
try {//监控区域
System.out.println(a/b);
}catch(ArithmeticException e){//想要捕获的异常类型,
System.out.println("出现错误,被除数不能为0");
}finally {
System.out.println("finally");
}
//try catch必须要,finally可以不要,但是它可以处理一些善后工作,比如关闭IO流、资源······
}
public static void main(String[] args) {
int a = 1;
int b = 0;
//如果要捕获多个异常,要从小到大的捕获
try {//监控区域
System.out.println(a / b);
;
} 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");
}
//try catch必须要,finally可以不要,但是它可以处理一些善后工作,比如关闭IO流、资源······
}
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(1);//手动的结束程序
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
public static void main(String[] args) {
try {
Test3 test3 = new Test3();
test3.test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
}
}
//如果在方法中处理不了这个异常,那么在方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
//主动的抛出异常,一般在方法中使用, 一旦在
if(b==0){
throw new ArithmeticException();
}
System.out.println(a/b);
}
public class MyException extends Exception{
//当数字>10时抛出异常
private int detail;
public MyException(int a) {
this.detail = a;
}
//to string打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
‘}‘;
}
}
//=========================================
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(11);
} catch (MyException e) {
//增加一些异常处理的代码块
System.out.println("MyException=>"+e);;
}
}
}
1. 处理运行的异常时,逻辑去合理规避同时辅助try-catch处理
2. 在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
3. 对于不确定代码,也可以加上try-catch,处理潜在的异常
4. 尽量去处理异常,切记只是简单地条用printStackTrace()去打印输出
5. 具体如何处理异常,要更具不同的业务需求和异常类型去决定
6. 尽量添加finally语句去释放占用的资源
原文:https://www.cnblogs.com/Running-Man/p/14821816.html