针对以下用例的Java异常处理

时间:2017-05-20 16:49:45

标签: java exception-handling instanceof

我的代码如下。

问题是:

是否有更好的方法来处理除此之外的以下用例的异常?

我特别感兴趣的是使用handleException方法。

public void checkSomeBehaviour() throws Exception{

    try{

        someBusinessValidation() ; 
        //this method can throw BusinessValidationException which is subclass of Exception 
        //BusinessValidationException contains code in getMessage() method


        try{    
            doSomething();  
        }catch(Exception ex1){  
                //throw Exception object with specific error code say 123. So this needs to be wrapped in separate try/catch


                throw CustomException('123');    //CustomException is subclass of Exception
        }       
        try{    
            doSomethingElse();      
        }catch(Exception ex2){  
            //throw Exception object with specific error code say 456 .So this needs to be wrapped in separate try/catch
            throw CustomException('456');       //CustomException is subclass of Exception  
        }

    }   
    catch(Exception ex){

        //Based on Exception type , a common exception needs to be thrown as ValidationException 
        handleException(ex);

    }


}
//this method inspects exception type and does appropriate action accordingly  
private void handleException(Exception ex){


    if(ex instanceof CustomException){
        throw new ValidationException(ex.getCode());
    }else if(ex instanceof BusinessValidationException){    
        throw new ValidationException(ex.getMessage());
    }else{
            throw new ValidationException(100); //throw code as 100 since this is generalised exception
    }

}

2 个答案:

答案 0 :(得分:0)

答案是:是的。 Java为您提供了本机语法(更简洁,更简单,比检查异常类更合适):<​​/ p>

let bundle = Bundle(identifier: "com.myframework")

请注意,如果它们相互延伸,您可能需要重新排序这些捕获块。

答案 1 :(得分:0)

如果您在方法调用之间没有任何业务逻辑,那么您可以将<input value.two-way="variable">声明为变量,在方法执行后更改它并在errorCode中重新抛出相应的异常,例如:

catch

如果public void checkSomeBehavior() throws Exception{ int errorCode = 123; try{ someBusinessValidation(); doSomething(); errorCode = 456; doSomethingElse(); }catch(BusinessValidationException bve){ throw new Exception(bve.getMessage()); }catch(Exception e){ throw new Exception(String.valueOf(errorCode)); } } 失败,则值为123,如果doSomething失败,则值为456.