Avoid empty catch blocks

本文探讨了在编程中使用空catch块的不当之处,并提供了在捕获异常时进行有效处理的一些建议,包括通知用户、日志记录、发送邮件给管理员等方法。同时强调了在不同情况下采取的适当行为,例如当异常不代表bug时,仅告知用户问题即可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.javapractices.com/topic/TopicAction.do?Id=16

Most contend that it's usually a very bad idea to have an empty catch block.

When the exception occurs, nothing happens, and the program fails for unknown reasons.

Example

The "tried our best" comments below are an example of what not to do : 

import java.io.*;
import java.util.*;
import java.nio.file.*;

/** How NOT to implement a catch.  */
public final class BadCatch {

  public static void main(String... arguments) {
    List<String> quarks = Arrays.asList(
      "up", "down", "charm", "strange", "top", "bottom"
    );   

    //serialize the List
    Path path = Paths.get("quarks.ser");
    try(
      ObjectOutputStream output = new ObjectOutputStream(Files.newOutputStream(path))
    ){
      output.writeObject(quarks);
    }
    catch (IOException ex) {
      //TRIED OUR BEST
    }
  }
} 

In general, when a exception occurs, it can be thrown up to the caller, or it can be caught in a  catch  block. When catching an exception, some options include:
  • inform the user (strongly recommended)
  • log the problem, using the JDK logging services, or similar tool
  • send an email describing the problem to an administrator

Deciding what exactly to do seems to depend on the nature of the problem. If there's an actual bug in the program - a defect that needs to be fixed - then one might do all three of the above. In this case, the end user should likely be shown a generic "Sorry, we goofed" message, not a stack trace. It's usually considered bad form to display a stack trace to a non-technical end user, or if exposing a stack trace may be a security risk.

If the exception does not represent a bug, then different behavior may be appropriate. For example, if a problem with user input is detected and an exception is thrown as a result, then merely informing the user of the problem might be all that is required. 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值