0

我有类似下面的Java方法:异常在Java中处理有Java的最佳实践

private boolean getBooleanProperty(String property, String defaultValue) { 
     boolean result = false; 
     try { 
      result = Boolean.parseBoolean(properties.getProperty(property, defaultValue)); 
     } catch (IllegalArgumentException | NullPointerException e) { 
     } 
     return result; 
    } 

我知道我处理在上述方法中的例外情况的方式是不正确的,并寻找有办法那些更符合Java标准和最佳实践。

同样,对于下面的方法:

public void getStatusAndAnnotation(ITestResult result) { 
     try { 
      HashMap<Object, Object> map = new HashMap<>(); 
      Method method = result.getMethod().getConstructorOrMethod().getMethod(); 
      TestInfo annotation = method.getAnnotation(TestInfo.class); 
      try { 
       //add id removing the first character of the annotation (e.g. for C12034, send 12034) 
       if(annotation!=null) { 
        map.put("id",annotation.id().substring(1)); 
       } 

      }catch (NullPointerException e){ 
       e.printStackTrace(); 
      } 
      if (result.getStatus() == ITestResult.SUCCESS) { 
       map.put("result", 1); 
      } else if (result.getStatus() == ITestResult.FAILURE) { 
       map.put("result", 9); 
      } else if (result.getStatus() == ITestResult.SKIP) { 
       map.put("result", 10); 
      } 
      if (annotation != null) { 
       if(annotation.trDeploy() && !map.get("id").equals(null) && !map.get("id").toString().isEmpty()) 
       { 
        ApiIntegration.addTestResult(map); 
       } 
       else System.out.println("Deploying result was canceled, because test has annotation \"trDeploy: false\" or \"id\" has no value"); 
      } 

     } catch (SecurityException | IOException 
       | ApiException | NullPointerException e) { 
      e.printStackTrace(); 
     } 
    } 

如何处理这些不同的异常与最佳做法看齐?

+0

你不应该捕获运行时异常,如NullPointerException异常 – mariusz2108

+0

您应该删除两个第一异常,如果控制和最后一个catch只需使用 –

+0

永远不会捕获NullPointerException。它表明程序员错误 - 你应该修复一个,而不是绕过或压制。 – VGR

回答

1

我通常所做的就是让编译器/ IDE告诉我需要捕捉哪些异常,除非您想为特定原因捕获异常。这样,我就可以编写代码而不会产生不必要的异常,而且我的代码更干净。

这些类型的异常被称为Checked Exceptions

“在Java类层次结构,一个例外是,如果 从java.lang.Exception的继承检查异常,但不能从 了java.lang.RuntimeException所有的应用程序或业务逻辑异常都应该检查异常。“

try 
{ 
    // open a file (Compiler will force to either catch or throw) 
} 
catch (IOException ioe) 
{ 
    ioe.printStackTrace(); 

    // need to make a decision on what to do here 
    // log it, wrap it in a RuntimeException, etc. 
} 

至于Unchecked Exceptions

“未检查,未捕获的或运行时异常有例外,可以是 抛出而不被卡住或宣布”

String x = null; 

// this will throw a NullPointerException 
// However, you don't need to catch it as stated in some the comments 
x.toString(); 

你应该做的是防止

if (x == null) 
{ 
    x = "some default value"; // prevent the exception from happening. 
} 
x.toString(); 

这是否意味着你永远不应该捕获RuntimeException的

不,当然不是。这取决于场景。

拿这个例子

String number = "12345"; 

// You don't know if number is a valid integer until you parse it 
// If the string is not a valid number, then this code will 
// throw an Exception 
int i = Integer.parseInt(number); 

相反,你可以搭乘NumberFormatException异常。再次,这是预防的一种形式。

int i = 0; // some default 
try 
{ 
    i = Integer.parseInt(number); 
} 
catch (NumberFormatException nfe) 
{ 
    // Good practice to log this, but the default int is fine. 
} 

一些最佳实践

  • 不要捕捉,除非编译器会强迫你例外。
  • 如果您正在捕获检查的异常,请将其记录下来。如果你想让它遍历调用堆栈,你也可以将它封装在一个RuntimeException中。
  • 如果你想捕获一个RuntimeException,那么这样做的目的(即你可以设置一个默认值,并防止错误所有在一起。)
  • 没有一个方法链都抛出一个检查异常向上堆栈跟踪。这非常混乱,并强制所有调用方法捕获或抛出检查的异常。
  • 捕获一个RuntimeException只是为了记录它真的没有太大的目的。除非你将它记录在一个捕获所有位置。

包罗万象的实例

try 
{ 
    // entry point to application 
} 
catch (Throwable t) 
{ 
    // let all exceptions come here to log them 
} 
0

这些类型的异常被称为选中例外,他们不应该在开发阶段处理。抛出时,通常会在代码中指示错误。

虽然开发人员能够以编程方式处理这些异常,但不建议从它们中恢复,因为它们通常表示需要调查和技术解决的严重问题。

看看这篇文章对于了解常见的异常处理技术:

How to use exceptions effectively