Can Mingir
Can Mingir

Reputation: 345

How to write unchecked exception in java?

Is that possible to write unchecked exception in Java? Maybe would it be good idea to tell compiler don't check the throws while compiling?

How does JVM differ checked vs unchecked exception? Is it JVM or Java Class level?

Upvotes: 3

Views: 2591

Answers (5)

Darshan
Darshan

Reputation: 469

You have to write a class with extending RuntimeException class Similar to writing checked exception however we need to extend the RuntimeException class

Upvotes: 0

dimoniy
dimoniy

Reputation: 5995

It's pretty easy. All unchecked exceptions are subclasses of RuntimeException. Just make your exception class inherit from RuntimeException, and you should be good to go.

Upvotes: 0

Mureinik
Mureinik

Reputation: 312106

You simply need to extend java.lang.RuntimeException.

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

Unchecked exceptions are mainly compiler-level, as they internally get thrown around in the same way. Only differences are requirements of them being explicit in code and method signatures.

You create an unchecked exception by inheriting from RuntimeException as opposed to Exception.

JLS 11.2 states:

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

....

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

Upvotes: 6

Kayaman
Kayaman

Reputation: 73568

Any exception that extends RuntimeException is an unchecked exception. You can write your own the same way (by extending RuntimeException that is).

Upvotes: 0

Related Questions