-2
我有一些问题抛出我自己的异常。下面是代码:正确地抛出你自己的异常(使它不终止你的程序)
class MyException extends Exception {
private String message;
public MyException(String message) {
this.message = message;
}
@Override
public String toString() {
return "Something went wrong: " + message;
}
}
代码,其中MyException抛出:
static void expand(String input, String output) throws MyException {
try {
Scanner sc = new Scanner(new File(input));
//do something with scanner
} catch (FileNotFoundException e) {
throw new MyException("File not found!");
}
}
和主要方法:
public class Encode {
public static void main(String[] args) throws MyException {
expand("ifiififi.txt", "fjifjif.txt");
System.out.println("ok");
}
异常通常抛出,该消息被正常打印,但该程序被终止并且“ok”消息不被打印出来。
Exception in thread "main" Something went wrong: File not found!
at vaje3.Encode.expand(Encode.java:59)
at vaje3.Encode.main(Encode.java:10)
Java Result: 1
'扩展( “ifiififi.txt”, “fjifjif.txt”);'未包裹在'尝试-catch'子句,所以错误冒泡至'main'和,因为没有捕获它,终止程序 – Michael
即使在主方法中声明了异常,它仍然会退出。正如@Michael所说的那样,由于扩展周围没有任何尝试,所以没有调用ok。 – lordoku
Oookay,但是在主要的方法(超过展开方法)try/catch做什么?你如何得到MyException消息? – Rok