Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create my own unchecked Exception in Java?

Tags:

Is it possible to create my own unchecked exception in Java?

Basically, I'd like to

  • Have my own exception class, MyUncheckedException
  • That does not make me update all methods that call the method that throws this exception with a flood of own throws
like image 545
James Raitsev Avatar asked Feb 21 '12 03:02

James Raitsev


People also ask

How would you make your own checked exception?

To create a custom exception, we have to extend the java. lang. Exception class. Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.

Can you write your own custom exception class?

NET provides a hierarchy of exception classes ultimately derived from the Exception base class. However, if none of the predefined exceptions meet your needs, you can create your own exception classes by deriving from the Exception class.

Can you create your own exception?

Steps to create a Custom Exception with an Example CustomException class is the custom exception class this class is extending Exception class. Create one local variable message to store the exception message locally in the class object.

Can we throws unchecked exception?

The throw keyword in Java is used for explicitly throwing a single exception. This can be from within a method or any block of code. Both checked and unchecked exceptions can be thrown using the throw keyword.


2 Answers

Yes. Extend MyUncheckedException from RuntimeException. However, below is the guideline from documentation

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

like image 100
Aravind Yarram Avatar answered Sep 21 '22 15:09

Aravind Yarram


Yes - derive it from RuntimeException

Make sure that you do it for the right reason: as a rule, runtime exceptions indicate programming errors, rather than errors that a program could potentially react to in some meaningful way.

like image 31
Sergey Kalinichenko Avatar answered Sep 18 '22 15:09

Sergey Kalinichenko