浅析Java中的异常处理机制
异常处理机制
1、抛出异常
2、捕获异常
3、异常处理五个关键字:
try、catch、finally、throw、throws
注意:假设要捕获多个异常:需要按照层级关系(异常体系结构)从小到大!
packageexception;
/**
*Java捕获和抛出异常:
*异常处理机制
*1、抛出异常
*2、捕获异常
*3、异常处理五个关键字
*try、catch、finally、throw、throws
*注意:假设要捕获多个异常:需要按照层级关系(异常体系结构)从小到大!
*/
publicclassTest{
publicstaticvoidmain(String[]args){
inta=1;
intb=0;
/**
*trycatch是一个完整的机构体,finally可以不要
*假设IO流,或者跟资源相关的东西,最后需要关闭,关闭的操作就放在finally中
*/
try{//try监控区域
System.out.println(a/b);
}catch(ArithmeticExceptionexception){//catch(想要捕获的异常类型)捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally{//处理善后工作
System.out.println("finally");
}
System.out.println("--------------分隔符--------------");
try{
newTest().a();//无限循环
}catch(Errorerror){
System.out.println("Error");
}catch(Exceptionexception){
System.out.println("Exception");
}catch(Throwablethrowable){
System.out.println("Throwable");
}finally{
System.out.println("finally");
}
}
publicvoida(){
b();
}
publicvoidb(){
a();
}
}
捕获异常
快捷键:选中代码Ctrl+Alt+T
捕获异常的好处:程序不会意外的停止,trycatch捕获异常后程序会正常的往下执行
packageexception;
/**
*捕获异常快捷键
*选中代码后:Ctrl+Alt+T
*如:
*选中System.out.println(a/b);
*然后快捷键Ctrl+Alt+T
*/
publicclassTest2{
publicstaticvoidmain(String[]args){
inta=1;
intb=0;
try{
System.out.println(a/b);
}catch(Exceptionexception){
exception.printStackTrace();//打印错误的栈信息
}finally{
}
}
}
抛出异常
1、在方法中抛出异常:throw
2、在方法上抛出异常:throws
packageexception;
/**
*捕获异常
*抛出异常
*/
publicclassTest3{
publicstaticvoidmain(String[]args){
/**
*方法中抛出异常
*/
newTest3().test(1,0);//匿名内部类直接调用
System.out.println("------------分隔符-------------");
/**
*方法上抛出异常
*捕获异常的好处:
*程序不会意外的停止,trycatch捕获异常后程序会正常的往下执行
*/
try{
newTest3().test2(1,0);//匿名内部类直接调用
}catch(ArithmeticExceptione){
e.printStackTrace();
}
}
/**
*在方法中抛出异常:throw
*@parama
*@paramb
*/
publicvoidtest(inta,intb){
if(b==0){//throw
thrownewArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
/**
*假设在方法中处理不了这个异常,就在方法上抛出异常,然后捕获异常
*在方法上抛出异常:throws
*@parama
*@paramb
*@throwsArithmeticException
*/
publicvoidtest2(inta,intb)throwsArithmeticException{
if(b==0){
thrownewArithmeticException();
}
}
}
以上就是浅析Java中的异常处理机制的详细内容,更多关于Java异常处理机制的资料请关注毛票票其它相关文章!