美文网首页
异常处理笔记

异常处理笔记

作者: 数字d | 来源:发表于2022-03-18 18:48 被阅读0次

程序在运行过程中,如果环境检测出一个不可能执行的操作,就会出现运行时错误。例如,如果使用一个越界的下标访问数组,程序就会产生一个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

预定义的异常类:

Exception.png

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": "自定义业务类错误"
}

相关文章

  • 2.1.3 Python面向对象之异常处理

    点击跳转笔记总目录 Python面向对象之异常处理 一、错误与异常 二、异常处理 三、什么时候用异常处理 一、错误...

  • Java异常处理-检查性异常、非检查性异常、Error

    一、Java异常处理详解 Java异常处理-笔记中的@doublefan讲解得非常通熟易懂 二、检查型异常和非检查...

  • 异常处理笔记

    #异常处理 知识点 try—catch C#语言的异常...

  • 异常处理笔记

    程序在运行过程中,如果环境检测出一个不可能执行的操作,就会出现运行时错误。例如,如果使用一个越界的下标访问数组,程...

  • python异常处理笔记

    python标准异常 BaseException 所有异常的基类 SystemExit 解释器请求退出 Keybo...

  • golang笔记——异常处理

    函数返回值处理异常 golang为了避免像写Java一样滥用try catch,可以使用函数多返回值的特性来进行异...

  • java异常处理笔记

    try{ //正常业务 }catch(异常1 e1){ //0-n个catch块 //处理异常1 }catch(异...

  • Swift笔记:异常处理

    Swift版本:3.0+ 前言 异常,简单理解就是应用程序报错了。在开发中,程序出现异常是很正常的,这就需要我们要...

  • 章节笔记——异常处理

    异常出现,程序变得强大,异常是处理错误的机制 1. 用try...catch处理异常 处理程序员控制和用户输入有误...

  • Python3.5笔记——第9章 异常

    Python3.5笔记 第9章 异常 什么是异常 一般情况下,在Python无法正常处理程序时就会发生异常。异常是...

网友评论

      本文标题:异常处理笔记

      本文链接:https://www.haomeiwen.com/subject/jlmmdrtx.html