程序在运行过程中,如果环境检测出一个不可能执行的操作,就会出现运行时错误。例如,如果使用一个越界的下标访问数组,程序就会产生一个ArrayIndexOutOfBoundsException
的运行时错误。如果需要读取文件内容,文件存在,就会出现一个FileNotFOundException的运行时错误。
在Java中,异常会导致运行时错误。异常就是一个表示阻止执行正常进行的错误或者情况。如果异常没有被处理,程序将会非正常 终止。
1.分母为0示例
int num1 = 10;
int num2 = 0;
System.out.println(num1 / num2);
报错提示
java.lang.ArithmeticException: / by zero
2.数组越界,调用实现和报错提示
@RestController
@RequestMapping("/test")
public class TestExceptionController {
@RequestMapping(value = "sum",method = {RequestMethod.POST})
@ResponseBody
public String sumAllInfo(@RequestBody List<Integer> list){
System.out.println(list);
Integer total = 0;
try{
total = sumall(list);
String tail = total.toString();
return "succssful" + tail;
}catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.toString());
StackTraceElement[] traceElements = e.getStackTrace();
for (int i =0;i < traceElements.length;i++){
System.out.println("method :" + traceElements[i].getMethodName());
System.out.println("(" + traceElements[i].getMethodName() + ":");
System.out.println(traceElements[i].getLineNumber() + ")");
}
}
return "other ";
}
public Integer sumall(List<Integer> list){
Integer total = 0;
for (int i = 0; i <= list.toArray().length ;i ++){
Integer value = list.get(i);
total += value;
}
return total;
}
}
调用:
localhost:8080/test/sum?
参数
[1,2,3]
报错提示
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
3.非法参数异常捕获类的实现
package com.example.demo;
/**
* Copyfright(C),2022-2022,复兴元宇科技有限公司
* FileName:CircleWihException Author:yz Date:2022/3/18 14:43
*/
public class CircleWihException {
private double radius;
private Double area;
public CircleWihException(){
this(1.0);
}
public CircleWihException(double v) {
this.setRadius(v);
}
public void setRadius(double radius) throws IllegalArgumentException{
if (radius > 0){
this.radius= radius;
this.area = 3.14 * radius * radius;
}else {
throw new IllegalArgumentException("Radius can not be negative");
}
}
public double getRadius() {
return radius;
}
public Double getArea() {
return area;
}
}
接口控制器类异常抛出实现:
@RequestMapping(value = "/radius")
public String area(@Validated Integer radius){
try {
CircleWihException circleWihException = new CircleWihException(radius);
circleWihException.getArea();
}catch (IllegalArgumentException ex){
System.out.println(ex);
return "error";
}
return "succesful ";
}
使用APIFox或者postman调用接口
http://localhost:8080/test/radius?
radius=1
预定义的异常类:

Throwable是所有异常类的根。所有Java的异常类都直接或者间接的继承自Throwable。可以通过扩展Exception或者Exception的子类来创建自己的异常类。
异常类的三种主要的类型:系统错、异常和运行时异常
1.系统错误:(system error)是由Java虚拟机抛出的,用Error类表示,Error类描述的是内部系统错误。
2.异常:(exception)是用Exception类表示的,它描述的是由程序和外部环境所引起的错误,这些错误能被程序捕获和处理。
3.运行时异常(runtime exception)使用RuntimeException类表示的,描述的是程序设计错误。例如:错误的类型转换、访问一个越界的数组或者数值错误。运行时异常通常是由Java虚拟机抛出的。
RuntimeException和Error以及它们的子类都称为免检异常unchecked exception。所有其他异常都是必检异常checked exception 编译器会强制程序开发者检查并处理它们。
自定义业务异常类:
package com.example.demo;
/**
* Copyfright(C),2022-2022,复兴元宇科技有限公司
* FileName:BusinessException Author:yz Date:2022/3/18 16:15
*/
public class BusinessException extends RuntimeException{
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
private Integer code;
public BusinessException(int code,String msg){
super(msg);
this.code = code;
}
}
自定义全局捕获异常
package com.example.demo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* Copyfright(C),2022-2022,复兴元宇科技有限公司
* FileName:CustomBusinessExceptionHandler Author:yz Date:2022/3/18 16:12
*/
@ControllerAdvice
@ResponseBody
public class CustomBusinessExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Map<String,Object> businessExceptionHander(BusinessException businessException){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",businessException.getCode());
map.put("message",businessException.getMessage());
return map;
}
}
测试自定义异常类
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Copyfright(C),2022-2022,复兴元宇科技有限公司
* FileName:TestServiceController Author:yz Date:2022/3/18 17:22
*/
@RestController
public class TestServiceController {
@RequestMapping("/bus")
public String testResponseStatusException(Integer id){
System.out.println(id);
if (id == 0) {
throw new BusinessException(600, "自定义业务类错误");
}else {
return "successful";
}
}
}
测试请求
curl -i http://localhost:8080/bus?id=0
返回结果
{
"code": 600,
"message": "自定义业务类错误"
}
网友评论