java enums 怎么优雅处理异常

avatar
作者
筋斗云
阅读量:0

在处理异常时,可以在enum中定义一个handleException方法来处理异常,可以根据不同的异常类型进行不同的处理。下面是一个示例代码:

public enum ExceptionHandler {     FILE_NOT_FOUND {         @Override         public void handleException(Exception e) {             System.out.println("File not found: " + e.getMessage());         }     },     NULL_POINTER {         @Override         public void handleException(Exception e) {             System.out.println("Null pointer exception: " + e.getMessage());         }     };      public abstract void handleException(Exception e); }  public class Main {     public static void main(String[] args) {         try {             // Some code that may throw exceptions             throw new FileNotFoundException("File not found");         } catch (Exception e) {             ExceptionHandler.FILE_NOT_FOUND.handleException(e);         }     } } 

在上面的代码中,我们定义了一个ExceptionHandler枚举,其中包含了两种不同的异常处理方式。在main方法中,我们首先抛出一个FileNotFoundException异常,然后根据异常类型调用不同的处理方法来处理异常。这样可以使代码更加优雅和易于维护。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!