Java的异常
Gary
Java 的异常分类
异常:
example:
int a=5/0
数组越界访问
读取文件文件不存在
- 异常处理:程序返回安全的状态
- 允许用户保存结果,并以适当的方式关闭程序
- Throwable:所有错误类的祖先
- Error:系统内部错误或者资源耗尽。这个其实可以先不管的
- Exception:程序自己出了问题
- RuntimeException:程序自身的错误:如空指针,5/0,数组越界…
- 非RuntimeException:外界相关的错误
- 打开一个不存在的文件
- 加载了一个不存在的类
异常处理
- 允许用户及时保存结果
- 抓住异常,分析异常的内容
- 控制程序返回到安全的状态
标准语法格式
try…catch…finally:一种保护代码正常运行的机制
- 异常结构
- try…catch(catch可以有多个,下同)
- try…catch…finally
- try…finally
- try必须是要有的,catch和finally至少要有一个
解释
try:正常逻辑业务的代码
catch:当try块出现异常的时候,将会执行catch代码。若没有异常,绕开
finally:当try或者catch执行完之后都必须执行finally
attention:
catch块可以有多个,每个可以有不同的入口形参。已发生异常和某一个catch块中的形参会相匹配,catch不触发就会进入finally块
一个异常只能进入一个catch块
code example
Java自定义异常
1、继承类
一般会选择继承Exception和RuntimeException,如果不要求调用者一定要处理抛出的异常,就继承RuntimeException。
2、自定义异常类构造方法
code example
public class People {
String name="";
int age=0;
String sex;
public String getSex()
{
return sex;
}
public void setSex(String sex) throws Exception{
if("男".equals(sex) || "女".equals(sex))
{
this.sex=sex;
}
else {
throw new GendorException("性别必须是男或者女");
}
}
}
public class GendorException extends Exception {
public GendorException(String msg)
{
super(msg);
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
People p=new People();
try {
p.setSex("Male");
} catch (Exception e) {
System.out.println("设置性别出错了");
e.printStackTrace();//输出异常信息
}
}
}
Spring boot 实例
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
//返回404
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
public NotFoundException(Throwable cause) {
super(cause);
}
public NotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}