Reputation: 35597
Consider following statement
BufferedReader br=new BufferedReader(new FileReader("D:\\test.txt"));
Normally we have to throws
Exception
or we have to use try-catch
to handle the Exception
.
But if I want to use this in a static block as follows. Only thing can do is use try-catch
block to handle the Exception
. But can't use throws
here? What is the reason behind java
doesn't provide throws
here?
static {
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Let me add this too. The case the block not a static block similar rule apply here.
{
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
We can normally do if this in a method as follows
public static void main(String[] args) throws FileNotFoundException {
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
}
Upvotes: 0
Views: 315
Reputation: 451
It's a static block being run when the class is initialized. Since it's a checked exception, you cannot throw it as there's nowhere to catch it.
throwing an unchecked exception is possible, but it will crash the program, as neither that can be caught anywhere.
Instead, you can put the code in a
public static void init() throws FileNotFoundException
{
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
}
And then call that once on your program start up.
Edit: Removing the static
keyword doesn't change anything in the compiled result. It's just the syntax that allows it to be missing.
Upvotes: 6
Reputation: 136152
You can throw an exception from init block but it should be an unchecked exception. What you can do is this
static {
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
} catch (FileNotFoundException e) {
throw new IllegalStateException(e);
}
}
Upvotes: 0
Reputation: 40438
Since an exception escaping the static
block would cause an ExceptionInInitializerError
.
In other words, don't let Exceptions escape from a static initializer - handle them instead.
Upvotes: 0
Reputation: 12959
Well, static
code block like that is run when your class is loaded (ussualy after JVM starts), so throwing exeption here would crush your entire java program, as you cant catch it anywhere
Upvotes: 0