我有一个主类,其中我有类似于
void FooBar(String s){
try {
parseString(s);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
context.getCounter(Counters.ERROR).increment(1); // this increment doesnt increases
}
}parseString是
void ParseString(String s){
if (matcher.matches()) {
} else {
//throw exception
try {
throw new Exception("bad formatted N-triples");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}但由于某些原因,错误不会向上传播。在我的FooBar方法中,错误计数器不会递增,即使该函数得到的数据格式不正确。
如何向上传播此异常?
发布于 2013-09-20 06:32:51
,但由于某些原因,错误不会向上传播...
它没有向上传播的原因是你捕捉到了它。异常在被捕获时停止传播。
要么不在parseString中捕获它,要么在处理程序中重新抛出它;例如e.printStackTrace(); throw e;
然而,这可能会让你遇到更多的问题,特别是因为你在这里捕获/抛出的异常。问题是Exception是所有检查异常的根源:
由于它是一个检查过的异常,如果你想让这个方法抛出任何可能的检查过的异常,那么方法parseString必须声明它throws
Exception throws Exception是说这个方法可以抛出任何可能的检查异常...这使得呼叫者的生活变得困难。(在本例中不是...但总的来说。)我的建议如下:
Exception。选择一个更具体的(选中或未选中)异常,它反映了您试图报告的“异常事件”的含义……或者实现你自己的异常类。在这种情况下,抛出IllegalArgumentException可能会更好,尽管这是一个未检查的exception.Exception时小心地传播Exception.Error)异常,包括所有未检查的异常;即RuntimeExecption及其子类。发布于 2013-09-20 06:31:40
你要么不在ParseString中捕获它,要么用throw e;重新抛出它
一旦捕获到异常,除非您再次throw它,否则它不会被传播。
发布于 2013-09-20 06:34:08
检查您在这里所做的事情:
try {
throw new Exception("bad formatted N-triples");//You throw an exception!
} catch (Exception e) {//And immediately catch it!
e.printStackTrace();
}因为异常已被捕获,所以它将不会传播。相反,删除try/catch块并简单地抛出异常:
void ParseString(String s){
if (matcher.matches()) {
//code for reasons
} else {
//throw exception
throw new Exception("bad formatted N-triples");
}
}请注意,这实际上是一种糟糕的做法。你想说一些关于你的异常,并声明它:
void ParseString(String s) throws IllegalArgumentException {
if (matcher.matches()) {
//code for reasons
} else {
//throw exception
throw new IllegalArgumentException("bad formatted N-triples");
}
}周围的函数应该知道如何显式地处理这个异常,而不是因为它是一个通用的异常而举起手来。
https://stackoverflow.com/questions/18905974
复制相似问题