Throwing custom exceptions in Java versus built in exceptions - java

I'm a little confused because I want to be able to throw a custom exception in Java. To do this inside a function, I have to add throws MyException to the header of the function.
And then anything that calls that function in turn must add throws MyException or have a try-catch block. But why is this?
For example, when creating a Stack in java and calling the pop function, I don't have to have a try-catch and yet the pop method in Java throws a NoSuchElementException (or w/e it is) if there isn't an element on the stack.

NoSuchElementException is a RuntimeException (un-checked exception) and we don't need to handle or declare RuntimeExceptionS, thus the compiler wont complain, but instead throw it at runtime.
In the case of checked exceptions i.e., all the exceptions which are not subtypes of RuntimeException, the compiler will check for a suitable catch clause, enabling the program to continue its course of execution, after performing the operations within the catch; to do this, you need to handle them using try/catch blocks or declare them using the throws clause - delegating the responsibility of handling the exception higher up the call chain. If your custom exception is not a RuntimeException rules of checked exceptions apply to your custom exception as well.
Checked exceptions ---> Forced by the compiler to handle or propagate
Un-checked exceptions ---> Not checked by the compiler thus appears at runtime

Java has so called checked exceptions and unchecked exceptions. A checked exception must be declared in method signature, an unchecked exception does not need to be declared.
If you want to define an unchecked exception yourself derive it from RuntimeException insted of Exception.

you are supposed to throw or try-catch all checked Exceptions , its not required for RunTimeException and exception that you are talking about is a RuntimeException

See my answer to this question.
As a general rule of thumb, when deciding whether or not to create a custom exception class, I try and use the built-in exception classes as much as possible, where it makes sense to do so, e.g. IllegalArgumentException, etc.
Here is an example of how to create a custom RuntimeException, which, as you have discovered, will not require a try/catch/finally block, or a throws clause.
public class MyRuntimeException extends RuntimeException {
public MyRuntimeException() {
super();
}
public MyRuntimeException(String message) {
super(message);
}
}
public class MyClass {
public void go(int val) {
if(val <= 0) throw new MyRuntimeException("Val must be greater than 0.");
}
}

Related

How can you add use a method that throws an exception without using try/catch in java? [duplicate]

This question already has answers here:
Checked vs Unchecked exception
(7 answers)
Closed 1 year ago.
Sometimes when the JDK declares a method, e.g. Integer.parseInt(String s) it throws a NumberFormatException, yet when the method is called you do not need a try and catch, how can I do this in my own code?
It is little unclear what exactly you are asking about - unchecked exceptions or how to avoiding try-catch-finalize blocks.
Unchecked Exceptions
If you are interested in how a method can throw exception, without declaring throwing it (right before body), then beware, that Java programming language does not require methods to catch or to specify unchecked exceptions ("RuntimeException", "Error", and their subclasses).
In contrast, you always have to handle (or declare to throw) all the other types of exceptions.
Avoiding try-catch-finalize
If, however, you're questioning how to avoid try-catch-finalize blocks, then you may throw an exception to the caller, by declaring your method throwing it, as:
[access-modifier] return-type methodName() throws Exception {
...
};
Use the "throws" clause after method declaration.
Eg: public static void main(String[] args) throws IOException {
}
There are basically two kinds of exceptions. Checked and unckecked in Java. All exceptions derived from RuntimeException are unckecked and you don't have to catch these.
So if you create an own exception which extends RuntimeException you don't have to catch it. Also check the already existing ones as they often already fit your needs. Like IllegalStateException or IllegalArgumentException.
1)To create your own exceptions in Java, you need to extend the
class you want to create from the Exception class in Java. 2)Then,
you can throw your own exceptions by using the throw keyword where
you want to write the error you want to show by override its
constructor or the getMessage method from the Exception class in the
class you created. 3)If you don't want your own exceptions to be try
and catch, you need to extend it from the RuntimeException class.
This exceptions that don't need try_catch are extend from RuntimeException insted of Exception class.
You can create your own RuntimeException like this:
public class CustomException extends RuntimeException {
public CustomException(String msg) {
super(msg);
}
}
Here I leave you a link with more information about diferent exceptions and how to handle them:
https://howtodoinjava.com/java/exception-handling/checked-vs-unchecked-exceptions-in-java/

Why does this method that throws an exception not have to be in a try catch block when invoked?

I invoke a method that throws exceptions, but I don't need to place this method inside a try catch block in static void main(String args[]), even though this tutorial says I should get an error. Why is this? Below is my code and a link to the tutorial. I played around with the second example in the tutorial.
https://beginnersbook.com/2013/04/java-throws/?unapproved=133049&moderation-hash=486e9de11daa2c67068e84cdacd88794#comment-133049
public class Sample2 {
static void myMethod() throws ArithmeticException, NullPointerException {
System.out.println("myMethod has been successfully called");
throw new ArithmeticException("Arithmetic Expression has been thrown");
}
public static void main(String args[]) {
myMethod();
}
}
The tutorial has a subtle mistake: although it clearly states that there is one kind of exceptions that does not need to be caught, it fails to notice that the exceptions thrown in their own examples are unchecked, i.e. of the Runtime variety:
On the other hand unchecked exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for handling checked exceptions.
Replace ArithmeticException with an exception that you derive directly from Exception to see the error.
When talking about Exceptions in Java, only 2 main types are invoked: checked exceptions and unchecked exceptions.
The checked exceptions are checked in compile time: if you don't handle a checked exception (by using a try/catch block for example or the throws key word), the compiler will raise an error, in other words, it won't let you build your program, this is why you should always handle all the checked exceptions.
The unchecked exceptions are checked in runtime: your compiler will not raise an error if you don't handle these type of exceptions.
Now the question is: how can i distinguish between these two types when i am coding ?
You should first keep in mind that every exception in java should inherits from the "Exception" class.
Now, there is a simple way you can tell a unchecked exception from a checked one: any exception class that inherits from "RuntimeException" is considered an unchecked exception, and any class that inherits from "Exception" but not "RuntimeException" is considered is a checked exception.
In your case, the method you're invoking throws a ArithmeticException and a NullPointerException. But this two exceptions inherits from the "RuntimeException". So, according to the rule written above, these 2 exceptions are unchecked exceptions, and that's why you had no need to handle it when invoking your method myMethod().

Throwing Checked Exception vs Throwing a wrapped RuntimeException

At many places, I get several Checked Exceptions like IOException, ParseException, JSONException, etc. I had to make either of 2 choices -
Throw the same exception by adding throws at the end of method signature.
Wrap the checked Exception in a RuntimeException(or some custom implementation) and then throw it so that caller doesn't have to add throws clause everywhere and check the exceptions.
In the first case, I will have to put throws everywhere, but my client can decide not to die by catching the checkedException and continuing to work. In 2nd case, however the RuntimeException may actually force the client to fail, as generally people don't catch Generic/RuntimeExceptions everywhere. Also using 2nd approach makes it easier to use Java 8 lambdas which doesn't work well with Checked Exceptions.
Which one of the two is preferred over another and why? Is there any preferred practice to follow?
There are two kinds of exceptions: exceptions that can be expected for a call and exceptions that are in principle unexpected (and that the application code probably cannot work around in a meaningful way). For the first kind (e.g. IOException for a file operation), checked exceptions (with 'throws' at the end of a method signature) are great.
For the second situation, it is my opinion that it's fine to wrap it in a RuntimeException for the reasons that you state (not having to add throws everywhere). All software should be prepared to catch RuntimeExceptions at the top level as a 'last line of defense', or they accept that a RuntimeException will end the program (which is often acceptable for instance for command line applications).
An example for the second situation is that a necessary configuration file is missing. I would rethrow that IOException as a RuntimeException.
By the way, there is a third way that is often used: throwing an application-specific exception. For instance this exception could be called 'MyConfigurationException'. I think this is only useful if an application can catch this exception and handle it intelligently.
(1) Throw the same checked exception by adding throws at the end of method signature:
Use this if the caller can recover from the exception or at least has
to take some decision/progress based upon that
(2) Wrap the checked Exception in a RuntimeException(or some custom implementation):
Use this if the caller can't recover (Most of the Exceptions in
Spring/Hibernate frameworks follow this pattern)
There is a third option, which is to throw the same checked Exception but to 'soften' it. CheckedExceptions are enforced only at Compile time, and by casting your Exception to a Throwable, you can safely throw it without the compiler complaining. Here is an example implementation (available in cyclops-functions a library I contribute to - or you can copy and paste :) )
UPDATE Simplified ExceptionSoftener class as per Andy Turner's comment.
public class ExceptionSoftener {
public static <T extends Throwable> T softenedException(final T e) {
uncheck(e);
return e; //never reached.
}
private static <T extends Throwable> void uncheck(Throwable throwable) throws T {
throw (T) throwable;
}
}
public void methodThrowsIOException(){
throw ExceptionSoftener.softenedException(new IOException("checked exception, but no declaration required!"));
}

When do I have to surround with try/catch?

I have some piece of code:
public static void a() throws NumberFormatException {
return;
}
public static void b() throws InterruptedException{
return;
}
public static void main(String[] args) {
a();
b();
}
And Eclipse says that I have to surround try/catch to function call b(), but I do not have to do that with a() call. Why? How to make function make to surround with try and catch when is called?
Because InterruptedException is a checked exception and NumberFormatException is an unchecked expcetion.
For checked exception, compiler forces you to either surround them with try-catch block or declare them with throws, while for unchecked exceptions try-catch block is not compulsory.
As function a() throws NumberFormatException (unchecked exception) compiler do not force you to surround the function call with try-catch.
As function b() throws InterruptedException (checked exception) compiler forces you to either surround the function call with try-catch or declare them with throws.
NumberFormatException is not a checked Exception(i.e because it has java.lang.RuntimeException as its base class), which means that the developer is not forced to handle(its the developer's choice whether to handle it or not) when the developer chooses not to handle the exception and if the exception occurs, it will be handled by the JVM.
Where as InterruptedException (i.e because it has java.lang.Exception as its base class) is a checked exception which means that the developer has to handle it every time either by using a try-catch block or by declaring the exception in the Throws clause.
Take a look at this example.
This is because NumberFormatException extends RuntimeException - i.e. it is unchecked exception. While InterruptedException is checked exception - it should be catched in try...catch block, or you should add throws to main() method.
because NumberFormatException() is unchecked exception InterruptedException is checked, you have to surroud checked exceptions with try-catch, but you dont have to try-catch checked - every method would have try-catch then.
NumberFormatException is a RuntimeException -> unchecked
InterruptedException is a checked Exception
I found the Java Tutorial quite useful to learn about Java and its APIs, and in fact, I still use it from time to time:
http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
http://docs.oracle.com/javase/tutorial/
public class InterruptedException
extends Exception
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.
but for the first case it will not ask NumberFormatException is an unchecked expcetion.
All Exception that extends RuntimeException do not imply an explicit try-catch block. They are called Unchecked. Those exception were theoretically reserved to unrecoverable runtime errors thrown by VM. However they are now commonly used as lot's of people agree to say the Checked exceptions mechanism is a bad design concept.
You will commonly use Unchecked when your program cannot recover from the error and let them propagate to a transverse layer exception handling that will be in charge to properly log and / or display the error to user.
Checked exception are commonly used in cases where the caller will be expected to handle the error, because it is able to recover from it or will trigger specific behavior.
The Keyword throws declares that a method may throw that exception. While checked exceptions have to be handled with unchecked exceptions this is optional. In your case a throws a NumberFormatException which is derived from RuntimeException which is according to the definition an unchecked exception, see Section 11.2: Compile-Time Checking of Exceptions:
The unchecked exceptions classes are the class RuntimeException and
its subclasses, and the class Error and its subclasses. All other
exception classes are checked exception classes.
And according to the definition the InterruptedException which class b throws is a checked exceptions (must be caught in a try-catch block).
There are two ways in Java to handle exceptions -
1. surround try/catch
2. propagate exeption
you use try/catch block if you want to handle this exception locally. Basically, within the try block is a code that has a potential of throwing an exception.
but you use throws SomeException in the method signature if you want this possible exception to be handled by the calling method... this calling method can also propagate this exception further up... should all methods never try/catch this exception, it will be thrown by the Java Virtual Machine at execution time

Java what is the benefit of Throwing RuntimeException

What is the benefit of declaring (Unchecked Exception)throws exception along method signature b/c it does not force caller to keep in try catch block.
public void testRuntimeEx()throws RuntimeException{
if(1==1){throw new RuntimeException()}
}
//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx();
}
It still serves as documentation, especially if you do not use a generic RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException and also add some JavaDoc as to when that would happen.
In your example code snippet, it is pretty meaningless, though.
This declaring is a signal for developer who uses this code, that it throws RuntimeException.
But it doesn't smell good.
P.S. Code you posted will not compile:
throw RuntimeException
This is not correct throwing.
The benefit is that typically caller does not have anything to do with the exception. It catches it, wraps with other exception and throws again. Or, alternatively, declares the exception using throws keyword and becomes transparent for this type if exception.
I'd say that the described situation is typical for applications where we usually write business code and have one centralized place that handles all exceptions. It is not correct for APIs. For example if you are using library that implements SSH you are expecting it to throw IOException (or even more specialize exception) when something is going wrong.
if you throw custom unchecked exception it becomes more meaningfull rather catching system exception and unchecked exception does not force to catch too.

Categories