Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should methods that throw RuntimeException indicate it in method signature?

For example, many methods in frameworks/JDK might throw

java.lang.SecurityException  

but this is not indicated in the method signature (since that is a practice normally reserved for checked exceptions). I want to argue that declaring RuntimeExceptions in method sigs has many benefits (akin to static type checking for example). Am I drunk or otherwise?

like image 789
Jacques René Mesrine Avatar asked May 05 '09 10:05

Jacques René Mesrine


People also ask

Is throws part of a method signature?

One thing which no one has mentioned is a very important answer to your question: Why throws, on a method, is part of its signature? that throws , is NOT part of the method signature.

Is it good practice to throw RuntimeException?

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.

What happens when runtime exception is thrown?

The Runtime Exception is the parent class in all exceptions of the Java programming language that are expected to crash or break down the program or application when they occur. Unlike exceptions that are not considered as Runtime Exceptions, Runtime Exceptions are never checked.

Which of the following exceptions need not be declared as thrown in the method signature?

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.


1 Answers

I would not declare an unchecked exception in the signature, since it is misleading to the user of that API. It is no longer obvious whether the exception has to be explicitly handled.

Declaring it in the javadoc is a better approach since it allows someone to handle it if they think it is necessary, but knowing they can ignore it if they want. This makes the separation between checked and unchecked clear.

like image 113
Robin Avatar answered Oct 11 '22 10:10

Robin