以下用例的Java异常处理
我有下面的代码 问题是: 除此之外,还有更好的方法来处理以下用例的异常吗 我特别感兴趣的是使用以下用例的Java异常处理,java,exception-handling,instanceof,Java,Exception Handling,Instanceof,我有下面的代码 问题是: 除此之外,还有更好的方法来处理以下用例的异常吗 我特别感兴趣的是使用handleException方法 public void checkSomeBehaviour() throws Exception{ try{ someBusinessValidation() ; //this method can throw BusinessValidationException which is subclass of Except
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
}
}
答案是:是的。Java为您提供了本地语法来实现这一点(比检查异常类更简洁、更合适):
请注意,如果这些catch块彼此扩展,您可能需要对它们重新排序。如果在方法调用之间没有任何业务逻辑,那么您可以将
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));
}
}
如果
doSomething
失败,则值为123;如果doSomethingElse
失败,则值为456。是,我同意。但是,提供一个公共位置,通过检查异常类型而不是在每个方法中检查相同的捕获原因来处理异常,这不是很好吗?我们可以有许多这样的方法,其中需要相同的异常处理
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));
}
}