Exception exception

Why can't you catch InterruptedException like this:

try { System.in.wait(5) //Just an example } catch (InterruptedException exception) { exception.printStackTrace(); //On this next line I am confused as to why it will not let me throw the exception throw exception; } 

I went to http://java24hours.com , but he did not tell me why I could not throw an InterruptedException.
If anyone knows why, PLEASE tell me! I am desperate !: S

+7
java exception throw
source share
3 answers

You can throw it only if the method you write declares that it throws an InterruptedException (or base class).

For example:

 public void valid() throws InterruptedException { try { System.in.wait(5) //Just an example } catch (InterruptedException exception) { exception.printStackTrace(); throw exception; } } // Note the lack of a "throws" clause. public void invalid() { try { System.in.wait(5) //Just an example } catch (InterruptedException exception) { exception.printStackTrace(); throw exception; } } 

For more information, you should review checked exceptions.

(Having said that, calling wait() on System.in almost certainly does not do what you expect from it ...)

+13
source share

There are two kinds of exceptions in Java: checked and unchecked exceptions.

For the noted exceptions, the compiler checks whether your program processes them either by searching for them, or by specifying (with the throws ) a method in which an exception may occur that the method may cause such an exception.

The exception classes, which are subclasses of java.lang.RuntimeException (and the RuntimeException themselves), are thrown exceptions. For these exceptions, the compiler does not check - so you do not need to catch them or indicate that you can throw them.

The InterruptedException class is a checked exception, so you must either catch it or declare that your method can throw it. You throw an exception from the catch , so you must indicate that your method can throw it:

 public void invalid() throws InterruptedException { // ... 

Exception classes that extend java.lang.Exception (except for RuntimeException and subclasses) are checked by exceptions.

See the Sun Java Exception Tutorial for more details.

+3
source share

InterruptedException is not a RuntimeException exception, so you need to catch it or check it (with the throws clause on the method signature). You can only raise a RuntimeException and not be forced by the compiler to catch it.

0
source share

All Articles