try
{
if(ruleName.equalsIgnoreCase("RuleName"))
{
cu.accept(new ASTVisitor()
{
public boolean visit(MethodInvocation e)
{
if(rule.getConditions().verify(e, env, parentKeys, astParser, file, cu)) // throws ParseException
matches.add(getLinesPosition(cu, e));
return true;
}
});
}
// ...
}
catch(ParseException e)
{
throw AnotherException();
}
// ...
我需要在底部捕获中捕获抛出的异常,但我不能通过throws构造重载方法。怎么办,请指教?感谢
答案 0 :(得分:0)
创建自定义异常,在匿名类中编写try catch块并在catch块中捕获它。
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor !=null
{
sensorManager.registerListener(this,CountSensor,SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this,"Count Sensor not Availabe in this device !!",Toast.LENGTH_LONG).show();
}
现在
class CustomException extends Exception
{
//Parameterless Constructor
public CustomException () {}
//Constructor that accepts a message
public CustomException (String message)
{
super(message);
}
}
答案 1 :(得分:0)
正如已经建议的那样,可以使用未经检查的异常。另一种选择是改变最终变量。例如:
final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
SomeInterface anonymous = new SomeInterface() {
public void doStuff() {
try {
doSomethingExceptional();
} catch (Exception e) {
exceptionRef.set(e);
}
}
};
anonymous.doStuff();
if (exceptionRef.get() != null) {
throw exceptionRef.get();
}