Methods that throw an exception that do not require catching - java

Sorry if this is a very basic question
As for my understanding if you have a method that throws an exception, you are required to catch it (or throw it) whenever you will be using that method.
However some methods that throw an exception do not require me to catch it like:
int num = Long.parseInt(sampleString);
Can anybody shed some light please?

There are two types of exceptions in Java: checked and unchecked. The former needs to be catched while the latter does not. An unchecked Exception is a class that extends either RuntimeException, Error, or one of their subclasses.
Long#parseLong throws a NumberFormatException which IS-A RuntimeException. Thus, it's an unchecked exception and does not need to be caught.
References:
Unchecked Exceptions -- The Controversy

There are exceptions which extend from RuntimeException. These are known as unchecked exceptions and they do not have to be declared in your method signatures. Generally, these are reserved for things which have really gone wrong.

There are 2 types of exceptions in Java. Checked and unchecked. Unchecked exceptions don't need to be caught. A good example of an unchecked exception is NullPointerException; you can see that if developers needed to catch this exception code would be ridiculously complicated. It would be lunacy. The exception that parseInt throws in an unchecked exception.

Those are subclasses of the RuntimeException. RuntimeExceptions and its subclasses don't need to be caught. They are called unchecked exceptions.

Related

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.

Why are exceptions named checked and unchecked?

Why is the two exception types in Java named "checked" and "unchecked"? What is the reason behind those names?
If you call a method which is declared to throw a checked exception (such as IOException), the compiler will check that you're either catching it or declaring that you rethrow it. Likewise, in order to throw such a checked exception in the first place, the compiler checks that you've declared it as part of the method signature.
Basically, it's a little bit like type checking, except in terms of which exceptions can be thrown by a method.
The compiler doesn't perform any checking for unchecked exceptions - so they can be thrown by any method, without the method declaring them.
Checked exceptions are checked by the Java compiler: it checks that you catch them or declare them in the method signature.
"Checked" means that you either have to catch it or declare that your method throws it in the signature. Users of your method must catch your checked exceptions. Failure to do so will result in a compiler error.
"Unchecked" means that neither you nor users of your method are required to catch the exception. You are not required to declare it in a throws clause in your method signature.
In its earliest incarnation, Java chose the first one more often than not.
C# makes unchecked exceptions the default. Java developers have taken up that convention now, too.
In Java you can throw any Throwable. Throwable has two sub-classes: Error and Exception. When an Error is thrown a serious problem has occured that often has very little to do with your code. Such exceptions are not checked by the compiler and is an example of an unchecked exception.
Exception has a subclass called RuntimeException, those are often exceptions that indicate bugs in your code and can often occur in lots of places in most code. Examples are NullPointerException, ArrayIndexOutOfBoundsException, etc. These are also unchecked since you would litter your code with catches of these.
All other exceptions are checked since by the compiler and you must catch or throw them.

Why runtime exception is unchecked exception?

Generally if any class extends Exception , it becomes checked exception. Runtime exception also extends Exception. Then how is it unchecked exception?
Is it like they have a custom check in compiler for this special case?
EDIT : I have proper idea about checked v/s unchecked exception and their pros & cos etc. I don't accept differences between them in answer.
It's explicitly in the specification, section 11.1.1:
RuntimeException and all its subclasses are, collectively, the runtime exception classes.
The unchecked exception classes are the runtime exception classes and the error classes.
The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.
So yes, the compiler definitely knows about RuntimeException.
Yes. Any Throwable is a checked exception, except for Error, RuntimeException, and (direct or indirect) subclasses thereof.
However, these are checked by the compiler, not by the JVM; checked exceptions are a compile-time feature, not a run-time feature. (Update: And I now see that you've edited your question to specify "compiler" rather than "JVM". ☺)
To elaborate a bit further . . . it's not as though there were any sort of "checked-exception" interface. The logic is simply hard-coded: "any exception class is a checked exception unless it's a subtype of RuntimeException or Error".
Here is a useful link: http://www.javapractices.com/topic/TopicAction.do?Id=129
It explains the difference between unchecked and checked and gives some examples.
"It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked)."
As per 11.1.1. The Kinds of Exceptions
An exception is represented by an instance of the class Throwable (a direct subclass of Object) or one of its subclasses.
Throwable and all its subclasses are, collectively, the exception classes.
Note that a subclass of Throwable must not be generic (§8.1.2).
The classes Exception and Error are direct subclasses of Throwable.
Exception is the superclass of all the exceptions from which ordinary programs may wish to recover.
Error is the superclass of all the exceptions from which ordinary programs are not ordinarily expected to recover.
Error and all its subclasses are, collectively, the error classes.
The class Error is a separate subclass of Throwable, distinct from Exception in the class hierarchy, to allow programs to use the idiom "} catch (Exception e) {" (§11.2.3) to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible.
The class RuntimeException is a direct subclass of Exception. RuntimeException is the superclass of all the exceptions which may be thrown for many reasons during expression evaluation, but from which recovery may still be possible.
RuntimeException and all its subclasses are, collectively, the run-time exception classes.
The unchecked exception classes are the run-time exception classes and the error classes.
The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.
Run-time exception is called unchecked exception since it's not checked during compile time. Everything under throwable except ERROR and RuntimeException are checked exception. Adding Runtime exception in program will decrease the clarity of program.
class Divide {
public static void main(String [] args){
int a = 10;
int b = 0;
int c = a/b; // This will throw run time exception due to unexpected value of b.
}
}
Please read this link The Java™ Tutorials - Unchecked Exceptions — The Controversy

can't java unchecked exceptions be handled using try/catch block?

In a tutorial I found that Unchecked Exception can't be handled by your code i.e. we can't use try/catch block and the examples are exceptions like ArrayIndexOutOfBoundsException, NullPointerException. But these exceptions can be handled using try/catch block. I think i am not clear about the concept !!
Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with UncheckedException?
The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using throws, whereas with unchecked ones this is optional.
Unchecked Exception can't be handled by your code i.e. we can't use try/catch block
Sure we can - but we don't have to.
Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with Unchecked Exception?
Note that there are two keywords:
throw explicitly throws an exception object you created. throw new NullPointerException(); works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.
throws declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declared throws NullPointerException because that is pretty much a given).
All the unchecked exceptions can be treated in the same way as the checked ones - if you want, you can let them pass by declaring that the method throws them:
public void m() throws RuntimeException {}
Or you can catch them:
public void m() {
try {
// some code
} catch (RuntimeException re) {
// do something
}
}
It should be noticed, the class RuntimeException acts as a catch-all for the unchecked exceptions (since all the unchecked exceptions extend from it), much in the same way that the Exception class is the catch-all for checked exceptions.
As has been mentioned before, the only real difference is that for checked exceptions you have to handle them (by letting them pass or catching them) and the compiler will make sure of it - on the other hand, the handling of unchecked exceptions is optional.
It all boils down to the expected usage of each exception type - you're supposed do be able to recover from checked exceptions (or at least do something about them, when they occur), whilst for unchecked exceptions, there might not be a reasonable way to recover from them. This of course, is a bit subjective.
They can be handled, but you don't have to. If you don't handle them, they will propagate and climb up the calling methods stack, until one of them catches it. If none does, the program will crash.
Usually, the bottom line is that if a client can reasonably be expected to recover from an exception, then it should be a checked exception. If a client cannot do anything to recover from the exception, then it's ok to have it as an unchecked exception.
Also, checked exceptions are useful to document an API that you expect to be used by 3rd-parties. When they know your method can throw a specific exception, they will code accordingly and handle the case. If you only use unchecked exceptions, all bets are off.
A common pattern (some people don't like it, but in some cases it's ok when you know what you're doing) is to wrap thrown checked exceptions into unchecked ones.
try {
... code that can throw CheckedException ...
} catch (CheckedException oopsSomethingBadHappened) {
throw new RuntimeException("Something bad happened!", oopsSomethingBadHappened);
}
An easy way to think about the difference is to think the checking refers to the compile. If an exception is a checked exception, the compiler will check that your code either throws the exception or handles it in a try/catch block at compile-time. For unchecked exceptions, the compiler won't do such a check. You can handle checked/unchecked exceptions the same way (with try/catch/throws), the difference just lies in the checks the compiler performs. This post has a decent example.
In addition to Guillaume:
unchecked exceptions are usually programming errors, which should not happen at all if implemented correctly (index out of bound, null pointer, class cast,...) and therefore the caller/ user usually cannot do anything about them.
checked exceptions are thrown because it was outside of the control of the programmer (network not availabe, filesystem not available, concurrent modifications such as duplicated primary key,...)
errors are usually thrown by the JVM and the application usually has to stop (out of memory, stack overflow,...)
Yes, you can throw unchecked exceptions with throw. And yes, you can catch unchecked exceptions in a catch block.
Yes you can handle the unchecked exception but not compulsory. Actually it depends on application developer. Below is the possible reason where i think required to handle even unchecked exception.
If your application is large where many developers are calling each other API. It is better to handle the unchecked exception otherwise at the end your program will crash which stop the other functionality. So even the simple NullPointerException can stop your program working.
Imagine you have one scheduler which processing the user data and which is in million size and for the bad data you only want to print the log not to stop working for other good data. In that case if you have not handle the exception one bad data can stop your program
yes we can handle Runtime Exception, plz check below code
public class Demo {
static void m1() {
int a[]=new int [5];
try {
a[12]=2;
}catch(Exception e) {
}
}
public static void main(String[] args) {
m1();
try {
String s=null;
System.out.println(s.length());
}catch(Exception e) {
}
System.out.println("hello world");
}
}

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