异常

一、分类

1.受检异常(checked):程序可以预期处理的,从外部产生,如:网络断线、文件丢失。必须处理。

2.非受检异常(unchecked):程序缺陷或由于情况复杂引起程序无法正确处理,不要求必须对异常进行处理。

1)运行时异常:数组越界 runtime exception

2)错误:内存不足 error

二、异常类

Throwable的子类

1.Exception 受检异常  需进行处理

2.Errot 非受检异常  不处理

3.RuntimeException 非受检异常 尽量避免

三、异常处理方式

1.捕获(使用try-catch-finally语句)

try{
   // 执行语法
}catch(异常类型 变量名){
    //处理语句
   e.printstackTrace();     
}finally{
    //回收资源
}

 2.抛出(方法声明)

throw new Exception("主动抛出异常")
public int divide(int i,int n) throws Exception{//方法抛出受检异常
//......
}

3.捕获在抛出

public int divide(int i,int n) throws Exception{//方法抛出受检异常
//......
  try{

  }catch{
     throw new Exception("异常");
  }  

}
原文地址:https://www.cnblogs.com/zdf159/p/7262893.html