When do I have to surround with try/catch? - java

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

Related

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().

Handling Exceptions without try-catch

Suppose we have a method (not main) and it has this piece of code in it's body:
if (a > b) {
throw new IllegalArgumentException("Fail!");
}
Is it equivalent to try-catch way of handling an exception or including the throws in the signature?
There are 2 kinds of exceptions in Java: checked exceptions and unchecked exceptions.
When a checked exception is thrown, the method signature must add a throw declaration. The calling code should embrace it in a try-catch.
When an unchecked exception is thrown, the method signature should not add the throw declaration. The calling code is not obliged to embrace it in a try-catch.
How to distinguish between these two kinds of exceptions? An unchecked exception does extend RuntimeException.
IllegalArgumentException belongs to the unchecked exceptions.
If you throw a Exception you need to catch it or you need to add throws to the method.
But I think you are confused as that is a RuntimeException you are throwing. RuntimeException need not be handled by try catch blocks. So it is not = to having a try catch as it doesn't need one...
So you are really asking the difference between a checked vs unchecked exception.
It's better to include a try catch and handle what you are going to do when that exception comes up.
But the way you have it written, it'll just cascade up until it comes across a try-catch or something that takes care of the exception.
This is nowhere equivalent to try-catch handling or throws.
Here, your method is throwing an IllegalArgumentException, which has to be handled in the method definition with throws as throws IllegalArgumentException or the caller of this particular method has to use try-catch to handle the IllegalArgumentException thrown by this method.

Is it redundant to throw specific exception in Java's method?

Consider the following code snippet.
public static void main(String [] args) throws IOException
{
....
}
My assumption tells me that: Any exception be it arrayOutOfBoundsException or IOException, the program will get terminated since there is no catching of the exception (and the exception thrown is not general). However I do see people throws specific exception at the method signature.
My question: Is it redundant for doing this? (since any exception will cause the program to terminate)
If it is not redundant, what is the reason people do it do this way?
What catches the exception thrown by main method?
the program will get terminated since there is no catching of the exception
It may seem that way because the main method is where your program starts. But actually, the Java Virtual Machine (JVM) calls the main method and therefore technically it catches and handles any exception thrown by it.
The handling done by JVM is merely to print the stack trace of the exception in the error stream, then terminate your program*. Which is why you see that stack trace in the console (unless the error stream was redirected elsewhere, like a file) before the program terminates.
* If no other programs (such as live non-daemon threads) are running in the JVM, it will also terminate itself.
Why should it be declared?
However I do see people throws specific exception at the method signature.
Is it redundant for doing this? (since any exception will cause the program to terminate)
First, I should clarify that by writing throws, the programmer is not throwing the exception. The programmer is merely declaring that this exception may be thrown by the method, and a caller of the method must handle it in some way.
To take your example:
public static void main(String [] args) throws IOException
This is most likely added by the programmer because his program calls some method from another class that also declares this. Some common examples are:
public FileWriter(String fileName) throws IOException // a constructor can also throw exceptions
FileWriter.write(int c) throws IOException
The designer of this FileWriter class has made it mandatory for its user (the programmer) to handle the IOException. This is called a checked exception.
The two types of exceptions
A checked exception tells the user that during the program run, the scenario causing this exception is likely to happen even though it normally shouldn't (because we don't live in an ideal world). This suggests an environmental error and such an exception can be thrown even in the best program.
The other type of an exception is the unchecked exception. The reason why you don't declare NullPointerException (an unchecked exception) using throws is because the scenario causing it is not expected to happen during a normal program run. If it happens, this suggests a programming error and a badly written program.
How do you handle an exception?
There are two ways to handle the exception received in a method.
First is the way the programmer has done in your example. Simply throw that exception back to the caller.
Second is to use a try-catch block to handle it internally:
public static void main (String [] args) // no need to declare "throws IOException"
{
try {
/* some code here that may throw IOException */
} catch (IOException ioe) {
System.err.println("Uhhhh something went wrong!");
// or some logging can happen
ioe.printStackTrace();
System.exit(-6); // a custom error signal can be sent in termination
}
}
But again, why?
If it is not redundant, what is the reason people do it do this way?
They do it because Java forces checked exceptions to be handled explicitly, while unchecked exceptions can be left unhandled.
As I have already explained the two ways an exception can be handled, it should be noted that programmers may pick one way over another depending on the situation. For some methods it may make more sense to throw a caught exception to the caller, while for others it would make more sense to handle the caught exception internally.
Then there are those lazy programmers who just declares every checked exception with throws.
Notes
Both checked and unchecked exceptions can be handled using either of the two ways above. Unchecked exceptions give you the third choice of not handling it, which in turn gives the caller the choice of handling or not handling it.
If you declare an unchecked exception using throws, it will become a checked exception to the caller of your method.
You can also mix and match both ways. For example, you may handle a checked exception internally at any point in the method, even if it is declared to be thrown in the method signature. The throws declaration will only take effect where the checked exception is not handled internally.
The main method of a class can be called like any other regular static method in your program, just by passing in a String array of arguments. It is only special in the sense that the JVM calls this method when the class is started as a Java program. When you manually call the main method, you have to handle the checked exceptions that may be thrown.
If some code in main throws a checked exception (like IOException), you have to declare it in throws. The main method is just like a normal method in that regard (in fact, it's just like a normal method in all regards, except that it's also an entry point for the program).

Throwing custom exceptions in Java versus built in exceptions

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.");
}
}

Difference between java.lang.RuntimeException and java.lang.Exception

Someone please explain the difference between java.lang.RuntimeException and java.lang.Exception? How do I decide which one to extend if I create my own exception?
Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.
EDIT : These days people favor RuntimeException because the clean code it produces. It is totally a personal choice.
In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.
For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).
Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.
Before looking at the difference between java.lang.RuntimeException and java.lang.Exception classes, you must know the Exception hierarchy. Both Exception and Error classes are derived from class Throwable (which derives from the class Object). And the class RuntimeException is derived from class Exception.
All the exceptions are derived either from Exception or RuntimeException.
All the exceptions which derive from RuntimeException are referred to as unchecked exceptions. And all the other exceptions are checked exceptions. A checked exception must be caught somewhere in your code, otherwise, it will not compile. That is why they are called checked exceptions. On the other hand, with unchecked exceptions, the calling method is under no obligation to handle or declare it.
Therefore all the exceptions which compiler forces you to handle are directly derived from java.lang.Exception and all the other which compiler does not force you to handle are derived from java.lang.RuntimeException.
Following are some of the direct known subclasses of RuntimeException.
AnnotationTypeMismatchException,
ArithmeticException,
ArrayStoreException,
BufferOverflowException,
BufferUnderflowException,
CannotRedoException,
CannotUndoException,
ClassCastException,
CMMException,
ConcurrentModificationException,
DataBindingException,
DOMException,
EmptyStackException,
EnumConstantNotPresentException,
EventException,
IllegalArgumentException,
IllegalMonitorStateException,
IllegalPathStateException,
IllegalStateException,
ImagingOpException,
IncompleteAnnotationException,
IndexOutOfBoundsException,
JMRuntimeException,
LSException,
MalformedParameterizedTypeException,
MirroredTypeException,
MirroredTypesException,
MissingResourceException,
NegativeArraySizeException,
NoSuchElementException,
NoSuchMechanismException,
NullPointerException,
ProfileDataException,
ProviderException,
RasterFormatException,
RejectedExecutionException,
SecurityException,
SystemException,
TypeConstraintException,
TypeNotPresentException,
UndeclaredThrowableException,
UnknownAnnotationValueException,
UnknownElementException,
UnknownTypeException,
UnmodifiableSetException,
UnsupportedOperationException,
WebServiceException
An Exception is checked, and a RuntimeException is unchecked.
Checked means that the compiler requires that you handle the exception in a catch, or declare your method as throwing it (or one of its superclasses).
Generally, throw a checked exception if the caller of the API is expected to handle the exception, and an unchecked exception if it is something the caller would not normally be able to handle, such as an error with one of the parameters, i.e. a programming mistake.
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur. (from JLS).
In the classes that you design you should subclass Exception and throw instances of
it to signal any exceptional scenarios. Doing so you will be explicitly signaling the
clients of your class that usage of your class might throw exception and they have to
take steps to handle those exceptional scenarios.
Below code snippets explain this point:
//Create your own exception class subclassing from Exception
class MyException extends Exception {
public MyException(final String message) {
super(message);
}
}
public class Process {
public void execute() {
throw new RuntimeException("Runtime");
}
public void process() throws MyException {
throw new MyException("Checked");
}
}
In the above class definition of class Process, the method execute can
throw a RuntimeException but the method declaration need not specify that
it throws RuntimeException.
The method process throws a checked exception and it should declare that it
will throw a checked exception of kind MyException and not doing so will be
a compile error.
The above class definition will affect the code that uses Process class as well.
The call new Process().execute() is a valid invocation where as the call of form
new Process().process() gives a compile error. This is because the client code should
take steps to handle MyException (say call to process() can be enclosed in
a try/catch block).
Proper use of RuntimeException?
From Unchecked Exceptions -- The Controversy:
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.
Note that an unchecked exception is one derived from RuntimeException and a checked exception is one derived from Exception.
Why throw a RuntimeException if a client cannot do anything to recover from the exception? The article explains:
Runtime exceptions represent problems
that are the result of a programming
problem, and as such, the API client
code cannot reasonably be expected to
recover from them or to handle them in
any way. Such problems include
arithmetic exceptions, such as
dividing by zero; pointer exceptions,
such as trying to access an object
through a null reference; and indexing
exceptions, such as attempting to
access an array element through an
index that is too large or too small.
From oracle documentation:
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.
Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.
RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException
With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...
In simple words, if your client/user can recover from the Exception then make it a Checked Exception, if your client can't do anything to recover from the Exception then make it Unchecked RuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.
RuntimeException is a child class of Exception class
This is one of the many child classes of Exception class. 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.
The hierchy is
java.lang.Object
---java.lang.Throwable
-------java.lang.Exception
-------------java.lang.RuntimeException
Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.
If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.
There are two types of exception, You can recover from checked exception if you get such kind of exception. Runtime exception are irrecoverable, runtime exceptions are programming errors, and programmer should take care of it while writing the code, and continue execution of this might give you incorrect result. Runtime exceptions are about violating precondition ex. you have an array of size 10, and you are trying to access 11 th element, it will throw ArrayIndexOutOfBoundException
User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.
User-defined Exception can be Custom Checked Exception, if it is extending to Exception class
User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.
Define a class and make it a child to Exception or Run time Exception

Categories