exception - Java throwing Error and catching NullPointerException -


It's something I do not understand

The first example:

< P> Example 1 (GOOD):

  Public static zero main (string array []) {try {exception e = null; Throw e } Hold (Exception E) {}  

Everything is fine with ths code - The exception is thrown and caught. Example 2 (BAD):

Public static zero main (string arguments []) {try {exception e = faucet; Throw e } Hold (NullPointerException E) {}}

It will not be compiled because Cache Block NullPointerException can not hold which exceptions . It is not known what type of exception would be thrown.

java.lang.Object java.lang.Throwable java.lang.Exception - & gt; Thrown java.lang.RuntimeException java.lang.NullPointerException - & gt;

If this can not happen, let us change the exception to NullPointerException :

Example 3 (GOOD)

< Pre> public static zero main (string array []) {try {NullPointerException e = null; Throw e (NullPointerException E) {}

Simple and logical, but here's really funny:

Example 4 (good) - Do not know why ?: < / P>

  public static zero main (string array []) {try {error e = null; Throw e } Hold (NullPointerException E) {} <}  

If I enter error , how can I capture NullPointerException ? It does not make any sense.

There is:

Throwshell: error, exception

both error and exceptions sub- There is nothing with the class of code> throwable , but NullPoinTerException with error , this is an exception , no Error .

You are trying to throw a blank object, which fails, and Null pointer exception is to be thrown instead.

You should throw a new exception;

Just to clarify if you were asking why your second example does not compile, while the fourth example is:

Error and its sub-classes are uncontrolled There are exceptions, which can be triggered by any throws

Uncheck exception class are run-time exception categories and error squares .

()

This is the reason that you can throw error and hold exception And compile the code.

On the other hand, in your second example, you are trying to throw a check exception ( exception ) and hold a NullPointerException , Which is not a super-class of exception . This is the reason that unless you hold down the exception or your main method throws an exception .


Comments