我在理解现有代码时遇到问题。我想知道Java如何管理抛出异常并以相同的方法捕获它。我在其他问题中找不到它,所以我先举例子。用Java运行以下代码将输出什么?
public static void main(String [ ] args) {
try{
System.out.println("1");
method();
}
catch(IOException e) {
System.out.println("4");
}
}
public static void method() throws IOException {
try {
System.out.println("2");
throw new IOException();
}
catch(IOException e) {
System.out.println("3");
}
}
将是1 2 3还是1 2 4?
好,让我们检查一下:
public static void main(String [ ] args) {
try{
System.out.println("1"); //<--When your code runs it first prints 1
method(); //<--Then it will call your method here
}
catch(IOException e) { //<---Won't catch anything because you caught it already
System.out.println("4");
}
}
public static void method() throws IOException { //<--Your Signature contains a throws IOException (it could throw it or not)
try {
System.out.println("2"); //<--It will print 2 and thow an IOException
throw new IOException(); //<--now it throws it but as you're using a try catch it will catch it in this method
}
catch(IOException e) {//the exception is caught here and it so it will print 3
System.out.println("3"); //<--Prints 3
}
}
现在,如果您在catch
方法中删除了method()
子句,诸如此类,现在它将为您捕获它:
public static void main(String [ ] args) {
try{
System.out.println("1"); //<--When your code runs it first prints 1
method(); //<--Then it will call your method here
}
catch(IOException e) { //<---It will catch the Exception and print 4
System.out.println("4");
}
}
public static void method() throws IOException { //<--Your Signature contains a trows IOException (it could trhow it or not)
System.out.println("2"); //<--It will print 2 and thows an IOException
throw new IOException();
}
[记住,尝试捕获意味着:捕获或抛出它(其他人将捕获它,如果没有捕获,它将进入主要位置并停止您的过程)。
1 2 3将作为输出。
不是4,因为异常被捕获在method
的try-catch块中