The Java compiler seems inconsistent if there is some code that clearly can not throw an exception, and you write surrounding code that declares that the code can throw that
Throws
does not handle exception, It indicates the throwing exception upwards from where method will be called. In other words it will just pass exception to the caller.
While try...catch
block handles the exception, and that is why Java compiler will check if there is any exception to handle which is being caught in catch
block or not.
Those are two different thing, One is Throwing and another is Handling the exception and compiler will make his nose tilted on second one only...:p
From the JavaDoc :
Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions.
So, by providing try...catch
implementation, you are requesting compiler to do some more thing than just printing exception.
Another specific reason :
public void testException() throws FileNotFoundException {
File file = new File("test.txt");
System.out.println(file.exists());
Scanner scanner = new Scanner(file);
}
If you will observe the compiled code of above example by javap -c Test.class
you will find an Exception table will be created.
public static void testException();
Code:
0: new #2 // class java/io/File
3: dup
4: ldc #3 // String test.txt
6: invokespecial #4 // Method java/io/File."":(Ljava/lang/String;)V
9: astore_0
10: getstatic #5 // Field java/lang/System.out:Ljava/io/PrintStream;
13: aload_0
14: invokevirtual #6 // Method java/io/File.exists:()Z
17: invokevirtual #7 // Method java/io/PrintStream.println:(Z)V
20: new #8 // class java/util/Scanner
23: dup
24: aload_0
25: invokespecial #9 // Method java/util/Scanner."":(Ljava/io/File;)V
28: astore_1
29: goto 37
32: astore_1
33: aload_1
34: invokevirtual #11 // Method java/io/FileNotFoundException.printStackTrace:()V
37: return
Exception table:
from to target type
20 29 32 Class java/io/FileNotFoundException
So, When compiler won't find any code that is not throwing exception in try block, an compile time error will be there.
and Exception table will not be generated in case of throws
.