我正在用Java实现一个编译器类型检查器。我的typeChecking类由一些方法组成,如果给定的输入文件(程序)在语义上是错误的,这些方法就会抛出RuntimeExceptions。
现在发生的情况是,当我的程序发现错误时,它抛出异常,程序终止。我想要的功能是将所有异常消息保存在某个位置,如果在typeChecking类中发生异常,则在Main类中打印它们。
伪码示例:
// Main class part of code
public static void main(String[] args){
call typeChecking method
if an exception (or more) occurred in the typeChecking class
then print all the exception messages
else no semantic errors found
then do something else
}我的想法是创建一个静态String数组,并在其中添加所有异常消息。然后在我的Main类中,我将检查数组的大小是否为0。如果不是,这意味着异常发生了,否则不会。
有没有更好的方法来做到这一点?
发布于 2016-04-15 22:35:32
只需使用try-catch块来捕获异常,并对捕获的异常做任何您想做的事情。也就是说。
// Main class part of code
public static void main(String[] args){
boolean exceptionOccured = false;
try{
call typeChecking method
}catch(RuntimeException e){
exceptionOccured = true;
...print it or put in an array or whatever.
}
if(exceptionOccured)
do something else
}https://stackoverflow.com/questions/36649986
复制相似问题