Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Why is catching a RuntimeException using catch(Throwable exc) {} not considered a good programming practice? What is the right way to handle RuntimeExceptions?
Also, why does catch(Exception exc) {} not catch RuntimeException? How is this behavior implemented?
Usually, a RuntimeException indicates a programming error (in which case you can't "handle" it, because if you knew to expect it you'd have avoided the error).
Catching any of these general exceptions (including Throwable) is a bad idea because it means you're claiming that you understand every situation which can go wrong, and you can continue on despite that. It's sometimes appropriate to catch Exception (but not usually Throwable) at the top level of the stack, e.g. in a web server - because usually whatever's gone wrong with a single request, you normally want to keep the server up and responding to further requests. I don't normally catch Throwable, as that includes Error subclasses which are normally used to indicate truly catastrophic errors which would usually be best "handled" by terminating the process.
Fundamentally, when there's an error you need to be very cautious about continuing with a particular task - you need to really have a pretty good idea about what the error means, as otherwise you could go ahead with a mistaken assumption about the state of the world, and make things worse. In most cases (not all), simply giving up on a request is better than trying to carry on regardless of a mysterious failure. (It does very much depend on context though - you might not care what went wrong when trying to fetch one piece of secondary information, for example.)
As for catching Exception not catching RuntimeException - that's simply not true. The only odd thing about RuntimeException is that it (and subclasses) are unchecked exceptions, whereas Exception and all other subclasses of Exception are checked.
It boils down to the different types of exceptions there actually are.
Checked exceptions (that is, exception classes that extend Exception) are typically errors you can recover from.
Unchecked exceptions (that is, exception classes that explicitly extend RuntimeException) are those that indicate an error in either expected behavior or program state. You wouldn't get a NullPointerException if the state of an object wasn't null when you dereferenced it, of course.
Blanket-catching everything - either Exception or Throwable, which is far worse - is not a good practice because you're assuming that you can recover from any exceptional behavior. There are some cases in which you shouldn't, or realistically can't (i.e. OutOfMemoryError for catch(Throwable t)). Further, catching runtime exceptions indicates a code smell; it means that you're covering up a coding error.
Be explicit about what it is you're catching.
Aside: Yes, catch Exception will also catch RuntimeException, since Exception is a superclass of RuntimeException. Just the same, Throwable will catch Exception and Error, which is why it's worse to write catch(Throwable t).
Throwable is super class of all Exception checked and unchecked(RuntimeException) and error.
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.Error
Ideally catching error is not a good practice.
And as RuntimeException extends Exception so it catches all RuntimeExcption's.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
There is a compile time and a run time of Java code. There are checked exceptions and unchecked exceptions. Both, checked exceptions and unchecked exceptions, happen at run time.
None-the-less the base class of the unchecked exceptions is not called UncheckedException but RuntimeException. This is not directly intuitive.
How can we access the choice of name from a logical point of view? Why is it not just called UncheckedException vs. CheckedException?
Once you understand the logic behind the choice of a name, it is much more easy to work with it.
Javadoc of RuntimeException says:
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
It's called "Runtime" because it is the superclass of exceptions that can be thrown by the "Runtime System", aka the Java Virtual Machine and the Runtime Library.
It's not about "at runtime", but about the "runtime system".
The exceptions are those that the JVM can generate, such as NullPointerException, ArrayIndexOutOfBoundsException, NegativeArraySizeException, ArrayStoreException, ArithmeticException, as well as common exceptions from the "Runtime Library" that shouldn't normally be caught (unchecked exceptions), such as IllegalArgumentException NoSuchElementException, etc.
The compiler has no default instructions or algorithm to handle your run time exceptions. that's why its called Run Time Exceptions.
A compile time exception is NOT an exception, it is an error in the code.
Throwable is at the top off all exceptions. Underneath Throwable you have Error and Exception. Underneath Exception you have RuntimeException.
Java has two types of exceptions - checked and unchecked. Checked exceptions are enforced by the compiler (you have to declare them in the throws clause and catch them eventually). Unchecked exceptions are not enforced for catching or declaring in throws clause.
Throwable exists so that there is a parent for all exception types. You should never declare that you throw Throwable and never catch it (unless you really really really know what you are doing).
Error exists to indicate issues with the runtime environment, things that your program probably cannot recover from, such as a badly formatted class file or the VM running out of memory. You should not catch an Error unless you really know what you are doing.
Exception exists as the root for all non-programmer errors (see RuntimeException for the "exception" to this) , such as a file cannot be created because the disk is full. You should not throw, throws, or catch Exception. If you have to catch Exception make sure you know what you are doing.
RuntimeException exists to indicate all programmer error, such as going past the end of an array or calling a method on a null object. These are things that you should fix so that they do not throw exceptions - the indicate that you, the programmer, screwed up the code. Again, you should not catch these unless you know what you are doing.
Read : https://docs.oracle.com/javase/tutorial/essential/exceptions/
Is it just an unfortunate choice of name?
It is just a way to differentiate them.
Checked and no checked exceptions derive from the same base class : Exception.
Exception is checked at compile time and RuntimeException is not.
The Runtime prefix conveys that the RuntimeExceptions are designed to be thrown at runtime without that client code needs to handle them at compile time.
As said in my comment : Exception and UnCheckedException would be more natural as we often refer to checked and unchecked exceptions as we talk about them. Now, things are done since a long time and the API cannot be modified and replaced.
This question already has answers here:
Difference between java.lang.RuntimeException and java.lang.Exception
(12 answers)
Closed 6 years ago.
I am curious as to how certain exceptions fall into checked exception category whereas others fall on the other ?
I know the basic difference between compile time error (syntactical error etc - this is intuitive and understandable.) and runtime error(null pointer exception etc.).
But I will prefer a more detailed analysis , as to how compile time error is detected and why does IO exception falls in compile time , as Input and output is something that is expected only during runtime ?
Also some discussion on Illegal Argument exception is detected?
I don't think there is a rule. In old times, checked exceptions was way to go, but today people tend to like unchecked exceptions better. You will probably find a lot of discussions around this topic on the internet. You can think of checked exceptions as: "You really need to handle this here or else things will go really bad for you". Personally I usually convert checked exceptions to unchecked exceptions if I need to handle them further up the application stack.
At the VERY core, a "checked" exception is usually caused by external sources e.g. IOException (so at compile time) whereas a "runtime" exception can happen, well, anywhere and is usually dependent on variables (which can change at runtime). It is the programmers duty to prevent all runtime exceptions (checking for null, checking indexes etc) whereas a checked exception can be caused by e.g. a file being renamed/removed. These two have a lot of overlap and hence a specific 'border' is impossible to define.
Some exceptions have been decided to be labeled as runtime because forcing the programmer to catch and handle them each time would obfuscate the code way too much. Checked exceptions usually don't occur too often but when they do, need to handled accordingly (closing files in a finally block etc).
I don't believe there's a definite rule which separates the two, but there has definitely been quite some though process behind it.
How is IllegalArgumentException a runtime exception where IO exception
is a checked exception ?
This is because IllegalArgumentException extends RuntimeException (called unchecked exceptions or runtime exceptions) whereas IOException extends Exception (called as checked exceptions).
In other words, if any exception object (is of type java.lang.Exception) is thrown from a method or code block then it will be verified at compile time whereas if an exception object is of type RuntimeException, then it will NOT be validated at compile time i.e., it will be known only during the actual execution (runtime) of the program.
Also, note that, checked exceptions are meant for compile time validations (i.e., we can provide a recovery mechanism by catching the exception) and the compiler ensures that all the checked exceptions are either thrown using throws keyword or caught using catch which is known as Catch or Specify, you can look here.
Specifically it makes sense for IllegalArgumentException to be unchecked because it's thrown in a large number of core Java APIs. If an exception is thrown practically everywhere making it checked does no good.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
There are so many exceptions, and it is not easy to remember. Is there any rule to know which kinds of exception will fall in which type (runtime vs checked), so that we know in which case we need to catch and in which case we just throw an exception? Thanks!
First of all, no exceptions are compile-time exceptions. The differentiation is checked exceptions vs. unchecked exceptions. The differentiation is made by the compiler by behaving as if each and every operation (method, constructor and initializer block) signature always implicitly includes throws Error, RuntimeException in its declaration. This way, the handle-or-declare rule, which means the compiler forces you to either handle an exception in a catch clause or declare an exception with a throws declaration is disabled for Error and RuntimeException - they are always implicitly declared.
So we overall have the following categories:
Compiler-treatment:
unchecked exception (handling is optional): RuntimeException and Error
checked exception (handle-or-declare rule applies): All other exceptions, including Throwable.
Categories:
Error - we usually do not catch these.
RuntimeException - catching depends on root cause.
Exception - we must handle or declare them (compiler enforces).
Error is easy to remember. If the VM or one of its APIs thinks it's a defect of the VM or the API that causes the issue, it's an Error. Usually we do not catch Errors, although there are a few prominent examples, like these:
catching OutOfMemoryError in resource allocating code to let the application continue after displaying an error message to the user. I.e. the user wants to load an image that's too big.
catching AssertionError in Unit Test frameworks. (They actually catch Throwable, but AssertionError is treated specially, it's a test failure, not a test error.)
Runtime exceptions are exceptions which do not happen if the program was written correctly, as long as the conditions that could lead to these exceptions do not depend on the user. For example, Integer.parseInt(String) throws NumberFormatException. If the String that is converted is coming from the program itself, it should be correct and we wouldn't care about the exception. If the String that is converted is coming from the user, we would usually rather catch NumberFormatException than letting the user crash the program by means of faulty input.
Other exceptions are used where the fault condition is somewhat likely but the program is always expected to handle them in some way. For example, if you open a file, it could always be that the file doesn't exist, cannot be read due to lack of permissions or locking, or that the storage is corrupt.
If you want to be new about things just catch everything... (horrible idea though only for the lazy) Otherwise look at the javados and it will tell you what is throw with each method.
try {
// this code
} catch (Exception e) {
e.printStackTrace();
}
Yeah if you have an issue at compile it means it just doesn't compile therefore doesn't exist and cannot run.
Do not catch RuntimeExceptions and Errors, catch other exceptions or add throws to method declaration
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Concerning the holy war question about choosing the proper exception in case of a null argument, I wonder if this choice has any practical consequences. I mean, is there a case when you'd catch a NullPointerException and not IllegalArgumentException, or vice versa, or catch both and handle them differently?
To make it clear: This is definitely not the linked question. I'm not asking what exception to throw... I'm asking if they ever get handled differently. I know that with both being RuntimeExceptions they hardly ever get caught, but sometimes you have to do it.
The intent of both exceptions is quiet different
NPE - in most scenarios that I can think of it occurs due to programming errors, so should not be handled.
In case of null, NPE should be thrown in a fail fast manner as it affects the trace. For which I personally use Preconditions.checkNotNull(E ref, String message) of Guava.
IAE - This means there that the class did not expect such a value from the caller. There can be scenarios when you can catch that exception and use default value for recovering.
I know that with both being RuntimeExceptions they hardly ever get
caught
According to me this is quite a misconception that Runtime exceptions are hardly ever caught. Nowadays APIs are depending more on Runtime exceptions as they want to leave on the caller to decide whether the exception gets caught. Many APIs impose you to catch many exceptions which leads to a lot of pain when you know that exception is never going to occur. You are forced to catch it and leave an empty catch block or better log that it should not occur.
The APIs do however specifically document when a particular exception is meant to occur.
Take an example of Integer.parseInt(String s) which throws NumberFormatException and which is a Runtime exception, in most scenarios when I have used it I always catch it and do some recovery using default values.
Think of the scenario if NumberFormatException would have been a checked exception, and you making a call Integer.parseInt("1"), it is clearly visible that it won't occur but still you will be forced to catch it. Agreed that the example is a hypothetical one, but gets my point through.
Again this is just my opinion based on my experience.
I'm asking if they ever get handled differently.
As I have wrote NPE is not caught in most scenarios, but there are always exceptions. Like suppose there is a part of your system that is kept open for extension for someone else to program and there is NPE in that code and you don't want the upper layers to be affected by it then I catch NPE and remove that component from the system giving proper logs and traces. A concrete example is a pluggable system, I didn't want my whole system to crash due to programming error in a user written plugin. So I caught Exception. This may be a bad example for others but worked for me.
IllegalArgumentException can be caught when sanitizing a user input based on criteria known only in the throwing method. It is a more subjective notion, and therefore I sometime catch it.
null you can always test yourself.
I don't think there is any difference from a technical point of view. I'd say stick to a strategy and document it as best as you can. Moreover, these are runtime exceptions, so they are not meant to be caught as they should happen in case of bugs or when a client calls a method/service without providing all the required parameters. Let it crash!
About the holy war question, I do believe NPE should only happen when a client tries to access a variable they think is not null but is, indeed, null and thus never thrown directly. IAE is more appropriate if a client expects a non null value and receives a null from a caller. This is IMO, don't want to take part in the feud.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am studying Java these days, and I have realized that it is important to handle exceptions in my codes.
I just what to ask how to handle exceptions with various methods?
Is it to examine the method I use to see what exception the method has thrown? In the example below I have to see what exception method m() throws.
try {
m();
} catch(SomeException e) {
...;
}
Is there any train of thought to handle exceptions when programming with Java?
The main skill to learn is how to not catch exceptions, but let them propagate up the call stack into the exception handler at the appropriate level.
Some rules of thumb:
catch the exception early (close to where it appeared) only if you have an actual escape route, a different way to complete the request in progress;
either log the exception or rethrow it, never both;
the place high up in the call stack is called the exception barrier: this is the unique place where to log the exception as an error;
don't be mislead by checked exceptions: most of the time the checked/unchecked distinction is not salient. Rethrow the checked exception (wrapped in a RuntimeException) when you have no code in mind to recover from it, which is the case most of the time. You could also declare the exception in your method header, but that is rarely practical;
be very careful not to let an exception result in a resource leak: all the acquired resources must be released in the finally block.
Reading these lines you'll note that most issues around exceptions are not demonstrable on minimal, textbook examples. Exceptions are about the information and control flow in fat codebases.
You really need to do a few tutorials on exception handling, you could use:
try {
m();
} catch(Exception e) {
e.printStackTrace();
}
to see what exception is being thrown and then read up on it.
Usually you need to log the exception, at least. And when
catching the exception make sure your catch block is not empty.
Some of them you can handle, some you cannot (for them you
usually need to fix your code as they indicate a bug in it).
So some are expected, others are programming errors.
Some are RuntimeExceptions (unchecked), others are not RuntimeExceptions
(i.e. are checked). RuntimeExceptions you don't need to declare in methods
or catch (i.e. you're not forced to do so by the language itself).
http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
The subject is too broad.
Try with samples like this as mentioned in below links that will give you clear clarification about the exception handling Do it with practically bro...
The 'Throwable' class is the superclass of all errors and exceptions in the Java language
Exceptions are broadly classified as 'checked exceptions' and 'unchecked exceptions'. All RuntimeExceptions and Errors are unchecked exceptions. Rest of the exceptions are called checked exceptions. Checked exceptions should be handled in the code to avoid compile time errors.
Exceptions can be handled by using 'try-catch' block. Try block contains the code which is under observation for exceptions. The catch block contains the remedy for the exception. If any exception occurs in the try block then the control jumps to catch block.
If a method doesn't handle the exception, then it is mandatory to specify the exception type in the method signature using 'throws' clause.
We can explicitly throw an exception using 'throw' clause.
http://java2novice.com/java_exception_handling_examples/
http://www.programmingsimplified.com/java/tutorial/java-exception-handling-tutorial