【问题标题】:Avoiding nested try/catch避免嵌套的 try/catch
【发布时间】:2015-07-20 08:13:45
【问题描述】:
import java.util.Scanner;

public class Test{

    public static void main(String[] args){

    Scanner input = new Scanner(System.in);
    String str = input.next();
    int a;
    try{
        try{
            a = Integer.parseInt(str);
        }
        catch(NumberFormatException nfe){
            throw new CustomException("message");
        }
        if (a>50) throw new CustomException("message");
    }
    catch(CustomException e){
        //do something
    }
}
}

如果str 不是数字,parseInt 将抛出一个NumberFormatException。但我想“转换”它,这样我就会有一个带有“消息”的CustomException。我可以不使用上面的嵌套 try/catch 块来执行此操作吗?

【问题讨论】:

  • 这是您的确切用例吗?如果是这样,那么您不需要做任何事情,您可以捕获 NumberFormatException。
  • if (a>50) throw new CustomException("message")??
  • 你的意图是什么?闻起来像XY-problem。也许您可以将CustomException 替换为IllegalArgumentException
  • 在继续之前先看看“异常链”。在我写这篇文章时的答案是垃圾。
  • @Turing85 err...是的也许...但我只是想知道我是否可以在 catch 块中重新抛出异常并在方法中处理重新抛出的异常而不使用嵌套的 try/catch块。

标签: java exception exception-handling nested try-catch


【解决方案1】:

你可以将你的例子改写为

 try {
     a = Integer.parseInt(str);
     if (a > 50) {
         throw new CustomException("message");
     }
 } catch (NumberFormatException | CustomException e){
     //do something
 }

【讨论】:

  • 您的第一个示例的行为方式与他的不同。你从不会被捕获的捕获中抛出一个CustomException
  • 当我调用 System.out.println(e.getMessage());在 catch 块中,NumberFormatException e 将给出“For input string: ~~”而不是“message”。
  • @tareviverat 是否相关,因为在这两种情况下您都有相同的信息?
  • 是的,我需要用一个方法处理所有抛出的异常,所以我需要在 catch 块中重新抛出一个 CustomException。
  • @tareviverat 您不必重新抛出异常,您可以将所有内容包装在函数中,并在调用函数的地方处理共享块中的异常
【解决方案2】:

使用 Scanner.hasNextInt() 解析 int 而无需担心异常。

详细代码见this question

【讨论】:

    【解决方案3】:

    你可以写:

    public static void main(String[] args){
    
        Scanner input = new Scanner(System.in);
        String str = input.next();
        int a;
        try{
            a = Integer.parseInt(str);
            if (a>50) throw new NumberFormatException("message");
        }
        catch(NumberFormatException e){
            //do something
        }
    }
    

    但我建议您使用您的版本,因为代码更具可读性。我的版本,即使去掉了内部尝试,也比你的可读性差。

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 2020-08-30
      • 2014-08-23
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      相关资源
      最近更新 更多