Reputation: 852
I have the below two sets of code
First Set of code is as below:
public static void main(String[] args){
try {
main(null);
} catch (Throwable e) {
}
System.out.println("Value of args[0] is : "args[0]);
}
Output is :
Value of args[0] is : db
Second set of code is as below:
public static void main(String[] args){
try {
main(null);
} catch (StackOverflowError e) {
}
System.out.println(args[0]);
}
Output is :
Exception in thread "main" java.lang.NullPointerException
at com.way2learnonline.ui.Demo.main(Demo.java:16)
In both cases I am passing a command line argument i.e. 'db'.
In first set of code I am catching Throwable in the catch block where I can access the command line argument i.e. args[0]
(I can see the args[0] output in the console).
In second set of code I am catching the StackOverflowError where I can not access the args[0]. It is showing NullPointerException.
I am not able to understand the behavior of Java.
Why I can access args[0] in first case and why args is null in second case.
Can someone explain why java is behaving like this?
Upvotes: 3
Views: 84
Reputation: 20254
In the first case you are catching all Exceptions, so when you call main
with a null value of args
the resulting NullPointerException
is caught and you don't see it.
In the second case you are only catching StackOverflowError
so the NullPointerException
that results from trying to access an element in a null array is not handled and you see the error.
It looks like you are just experimenting here, but it's worth saying that you should never catch StackOverflowError
in 'real' code.
Upvotes: 1
Reputation: 85779
StackOverflowError
will happen in both pieces of code.
The code catching StackOverflowError
will handle it in the last recursive call of the method, but since the catch
does nothing then the next line of code will be executed:
System.out.println(args[0]);
And this will throw a NullPointerException
since args
is null
and you cannot access to args[0]
.
The other one will handle every error or exception, including this NullPointerException
, and it will go up through all the methods in the call, so the exection of the code will continue. Seems like you're passing as argument "db"
, so that's what is printed.
Upvotes: 8