异常

异常:用于发现并反馈问题的一套机制

Throwable:异常的顶级父类

  Error —– 符合java语法以及逻辑,不需要处理

  Exception ----- 符合语法及逻辑的java程序,可以进行处理(抛出,捕获)

 

编译时异常,一定要处理:

例如:

  CloneNotSupportedException:克隆不支持异常

 

运行时时异常,编译没错运行出错,可处理,也可以不处理(统一父类,RuntimeException)

  NumberFormateException -- 格式化异常

  ArithmeticException -----算术异常

  ArrayIndexOutOfBoundsException:数组下标越界异常

  java.lang.NullPointerException:空指针异常:没有指向

  java.lang.ClassCastException:类型转换异常,编译没错,运行出错

 

没有catch块,则表明try块里的信息是没有异常的

  捕获异常方式:

    1.抛出的异常需要进行不同的处理操作,需要进行分别捕获

    2.抛出的异常需要进行统一的处理,对他们的父类进行捕获

    3.不好找到所有异常的统一父类时,抛出的异常时可以进行分组捕获(| 分割一组之间的异常 ),从JDK1.7出现

public class ExceptionDemo {
    public static void main(String[] args)  {
​
        try {
            String s = readTxt("C:\\a.txt");
        } catch (FilePathNotExitsException e) {
            System.out.println(e.getMessage());
            
        }catch(FileNotExitException e) {
            System.out.println(e.getMessage());
        }catch(NullPointerException e){
            //栈轨迹
            e.printStackTrace();
        }
        
        
        /*统一处理
        try {
            String s = readTxt("C:\\a.txt");
        } catch(Exception e){   //统一处理
            e.printStackTrace();
        }
        */
        
        //分组处理
        /*  try {
            String s = readTxt("C:\\a.txt");
        }catch(FileNotExitException|FilePathNotExitsException e) {
            System.out.println(e.getMessage());
        }catch(NullPointerException e){
            //栈轨迹
            e.printStackTrace();
        } 
        
        */
        
        
        //异常捕获之后,后面的代码可以走
        System.out.println("操作完成");
    }
    
    //异常是在方法上抛出,可以抛出多个
    public static String readTxt(String path) throws FilePathNotExitsException, FileNotExitException,NullPointerException{
        //给定路径不存在
        if(!path.startsWith("C")){
            //把问题进行反馈
            //当代码抛出异常,后面的代码就不走了
            throw new FilePathNotExitsException("亲,路径可能不存在...");
        }
        
        //给定路径指向的文件类型可能不是文本
        if(!path.endsWith("das")){
            throw new FileNotExitException("亲,文件可能不存在");
        }
        
        
        String s = "ADFADSFA";
        System.out.println(s);
        return s;
        
    }
}
​
//自定义异常类,要继承异常类
class FilePathNotExitsException extends Exception{
    
    private String message;
    
    public String getMessage() {
        return message;
    }
​
    public void setMessage(String message) {
        this.message = message;
    }
​
    public FilePathNotExitsException(String message){
        this.message=message;
    }
    public FilePathNotExitsException(){
        this.message=message;
    }
}
​
​
class FileNotExitException extends Exception{
     private String message;
​
     public String getMessage() {
        return message;
    }
​
    public void setMessage(String message) {
        this.message = message;
    }
​
    //调用父类异常的构造方法
    public FileNotExitException(String message){
         super(message);
     }
}

 

 

重写方法时:编译时异常注意点

import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
​
public class ExceptionDemo {
    public static void main(String[] args)  {
​
    }
}
​
class EDmo1{
    public void m()throws IOException{}
    public void m(int i) throws CloneNotSupportedException{}
}
​
class EDmo2 extends EDmo1{
    //方法进行重写时,子类不能抛出父类及其子类之外的异常(编译时异常)
    //运行时异常不受影响
    @Override
    public void m()throws EOFException,FileNotFoundException{}
    
}

 

 

finally表示异常捕获或者不捕获都要走的部分

  //代码从上往下执行

  //当检测到final块一定要去执行里面的内容,

  //如果上面操作有return,此时return 的操作就被挂起

  //检测final执行结束,重新回到挂起的位置继续执行

 

 

 

异常处理

1.全局异常处理案例

ApplicationExceptionMapper.java

package com.wiscom.exception;

import com.wiscom.Application;
import com.wiscom.common.ApiResult;
import com.wiscom.constant.CodeMsg;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@Provider
public class ApplicationExceptionMapper implements ExceptionMapper<Exception> {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Application.class);

    @Override
    public Response toResponse(Exception exception) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        exception.printStackTrace(new PrintStream(stream));
        logger.error("全局异常信息:" + stream.toString());
        return Response.ok(ApiResult.Fail(CodeMsg.SERVER_ERROR), MediaType.APPLICATION_JSON).build();
    }
}

ServiceException.java

package com.wiscom.exception;

/**
 * 业务层全局异常处理类
 * 专门处理Service层实现类中的各类业务异常信息
 */
public class ServiceException extends RuntimeException {
    private static final long serialVersionUID = 3733661059410867556L;
    public ServiceException() {
        super();
    }
    public ServiceException(String message) {
        super(message);
    }
    public ServiceException(Throwable cause) {
        super(cause);
    }
}

使用案例:

if (enterpriseVOList == null || enterpriseVOList.size() == 0)
            throw new ServiceException("地图中没有重大危险源企业");

 

posted @ 2020-08-18 22:03  minnersun  阅读(74)  评论(0编辑  收藏  举报