我正在为我创建的简单命令行工具创建自己的Exception类。基本上,目的是决定何时抛出致命异常并在这种情况下终止程序。所以我的ReconToolException类有一个布尔标志来记录致命的异常。
但是,我的问题是,“抛出”异常的正确方法是什么?
我应该这样做吗?:
if(columnNumberForGroupByColumnFile1 == null || columnNumberForGroupByColumnFile2 == null ||
columnNumberForCountColumnFile1 == null || columnNumberForCountColumnFile2 == null ){
new ReconToolException("Can't find column number. Likely that there are unexpected headers in the CSV files. Check your CSV configuration enum .java files to see if they match the actual input CSV files.");
}
还是应该按照以下方式进行?:
if(columnNumberForGroupByColumnFile1 == null || columnNumberForGroupByColumnFile2 == null ||
columnNumberForCountColumnFile1 == null || columnNumberForCountColumnFile2 == null ){
try {
throw new ReconToolException("Can't find column number. Likely that there are unexpected headers in the CSV files. Check your CSV configuration enum .java files to see if they match the actual input CSV files.");
} catch (ReconToolException e) {
e.printStackTrace();
}
}
前者似乎要求我在ReconToolException类中显式编写print out语句以将错误打印到命令行。后者将自我捕获(这很奇怪,老实说似乎不正确)并将在catch块中打印出堆栈跟踪。前者似乎更有意义,但后者似乎更好。有正确的方法吗?
这是我创建的Exception类:
public class ReconToolException extends Exception {
private boolean isFatal;
public ReconToolException() {
// TODO Auto-generated constructor stub
}
public ReconToolException(boolean isFatalException, String msg) {
super(msg);
this.setFatal(isFatalException);
}
public ReconToolException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ReconToolException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public ReconToolException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ReconToolException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public boolean isFatal() {
return isFatal;
}
public void setFatal(boolean isFatal) {
this.isFatal = isFatal;
}
}
答案 0 :(得分:4)
你应该只是throw
异常,没有自己在抛出它的方法中捕获它,除非你想在那里捕获它。通常你不会,如果你自己创建例外。此方法的其他调用者可能希望捕获它。
这将要求您修改方法签名以包含throws ...
向调用者指示您的方法可能抛出的异常:
if(columnNumberForGroupByColumnFile1 == null || columnNumberForGroupByColumnFile2 == null ||
columnNumberForCountColumnFile1 == null || columnNumberForCountColumnFile2 == null ){
throw new ReconToolException("Can't find column number. Likely that there are unexpected headers in the CSV files. Check your CSV configuration enum .java files to see if they match the actual input CSV files.");
}
...
答案 1 :(得分:2)
如果您遵循第二种方法(即捕获异常),则isFatal
标志没有意义。如果您只是抛出并立即捕获异常,那么您只是显示错误堆栈跟踪,并且不允许异常传播方法调用序列,因此它不能终止程序以防它致命。
你应抛出异常,让方法的调用者处理它。