沈阳市网站建设_网站建设公司_论坛网站_seo优化
2025/12/26 23:13:27 网站建设 项目流程

1.基本覆盖范围

try{// 可能抛出各种异常}catch(Exceptione){// 可以捕获所有继承自Exception的异常// 包括运行时异常和受检异常}

2.异常继承体系

Throwable (可抛出) ├── Error (错误) // catch(Exception) ❌ 不能捕获 │ ├── VirtualMachineError │ ├── OutOfMemoryError │ └── StackOverflowError │ └── Exception (异常) ├── RuntimeException // ✅ 可以捕获 │ ├── NullPointerException │ ├── IllegalArgumentException │ └── ArithmeticException │ └── 其他受检异常 // ✅ 可以捕获 ├── IOException ├── SQLException └── 自定义异常

3.重要限制:不能捕获Error

try{// 触发堆栈溢出错误recursiveMethod(0);}catch(Exceptione){// 这里不会执行!因为StackOverflowError是Error,不是ExceptionSystem.out.println("捕获到异常");}catch(Errore){// 需要这样捕获ErrorSystem.out.println("捕获到错误: "+e);}privatevoidrecursiveMethod(intdepth){if(depth>10000)return;// 应该有退出条件,但这里故意写错recursiveMethod(depth+1);}

4.捕获所有Throwable

如果要捕获所有异常和错误:

try{// 可能抛出任何Throwable}catch(Throwablet){// 可以捕获Exception和Errorif(tinstanceofError){// 处理严重错误log.error("发生严重错误",t);}elseif(tinstanceofException){// 处理普通异常log.error("发生异常",t);}}

5.Spring Boot中的实际应用

场景1:全局异常处理

@RestControllerAdvicepublicclassGlobalExceptionHandler{// 只能处理Exception及其子类@ExceptionHandler(Exception.class)publicResponseEntity<ErrorResponse>handleAllExceptions(Exceptionex){returnResponseEntity.status(500).body(newErrorResponse("系统异常"));}// 如果需要处理Error,需要单独定义@ExceptionHandler(Error.class)publicResponseEntity<ErrorResponse>handleErrors(Errorerror){// 通常记录日志后让应用关闭log.fatal("系统发生严重错误",error);returnResponseEntity.status(500).body(newErrorResponse("系统错误"));}}

场景2:Service层异常捕获

@ServicepublicclassUserService{publicUserprocessUser(Stringdata){try{// 业务逻辑returnparseAndSave(data);}catch(Exceptione){// 这里能捕获所有Exception// 但无法捕获VirtualMachineError等// 转换为业务异常thrownewBusinessException("处理用户失败",e);}}// 更完整的版本publicvoidcriticalOperation(){try{// 关键操作performOperation();}catch(Throwablet){// 捕获所有Throwableif(tinstanceofOutOfMemoryError){// 内存不足,尝试清理System.gc();thrownewSystemException("内存不足,请重试");}elseif(tinstanceofException){// 普通异常处理thrownewBusinessException("操作失败",t);}else{// 其他Error,重新抛出throwt;}}}}

6.Thread.UncaughtExceptionHandler

对于未捕获的异常(包括Error):

publicclassGlobalExceptionHandler{publicstaticvoidsetup(){// 设置默认的未捕获异常处理器Thread.setDefaultUncaughtExceptionHandler((thread,throwable)->{// 这里能捕获所有未处理的Throwableif(throwableinstanceofError){log.fatal("线程 {} 发生严重错误",thread.getName(),throwable);// 可能需要重启应用}else{log.error("线程 {} 抛出未捕获异常",thread.getName(),throwable);}});}}

7.最佳实践建议

不推荐的做法

try{// 所有代码}catch(Exceptione){// 什么也不做,或只是打印e.printStackTrace();// 生产环境无效}

推荐的做法

@ComponentpublicclassSafeExecutor{// 处理可恢复的异常public<T>Optional<T>executeSafely(Supplier<T>task){try{returnOptional.ofNullable(task.get());}catch(RuntimeExceptione){// 业务异常,记录并返回空log.warn("业务操作失败",e);returnOptional.empty();}catch(Exceptione){// 系统异常,需要关注log.error("系统异常",e);returnOptional.empty();}// 不捕获Error,让上层处理}// 处理需要区分异常的场合publicvoidprocessWithRetry(Runnabletask,intmaxRetries){intattempts=0;while(attempts<maxRetries){try{task.run();return;}catch(BusinessExceptione){// 业务异常不重试throwe;}catch(TemporaryExceptione){// 临时异常,重试attempts++;if(attempts==maxRetries)throwe;waitForRetry(attempts);}catch(Exceptione){// 其他异常,包装后抛出thrownewSystemException("操作失败",e);}}}}

8.重要总结

捕获类型能捕获的异常不能捕获的异常使用场景
catch (Exception e)所有Exception子类Error及其子类日常业务异常处理
catch (Throwable t)Exception和Error无(全部可捕获)框架底层、关键组件
catch (RuntimeException e)运行时异常受检异常、Error快速失败场景

关键点

  1. Exception能捕获所有异常,但无法捕获Error
  2. Error通常表示严重系统问题,不应随意捕获
  3. 生产环境中应该分层处理异常
  4. 不要用空的catch块"吞掉"异常
  5. 考虑使用Throwable的场景:线程池、自定义类加载器等

在Spring Boot项目中,通常建议:

  • Service层:抛出业务异常或记录后重新抛出
  • Controller层:使用@ExceptionHandler处理
  • 全局:使用@ControllerAdvice统一处理Exception
  • Error:由专门的监控系统处理

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询