Why are runtime exceptions called runtime exceptions in Java code? [closed] - java

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.

Related

Why my Ide is not warning me about handle this exception [duplicate]

I've studied that: With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
what its mean?
according to that code there is no need to put try catch block in code,
but i've seen compiler forces to put the code in try catch block.
I'm very confused what they are exactly?
Unchecked exceptions are those that extend RuntimeException class. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword. All other exception types (that do not extend RuntimeException) are checked and therefore must be declared to be thrown and/or catched.
Checked exceptions are used when you want the caller of your method (i.e the user of your API) to explicitly handle the exceptional case in your API. Checked exceptions are declared when you believe the call will be able to do something meaningful with that exceptional case, like retrying the call, rolling changes back or converting it into some user-readable error message.
If you believe that there is nothing useful the call can do about the exception (especially when it represents a bug, or a wrong usage of your API), then the exception should be unchecked. Also, an API with too many checked exceptions can be annoying to program with (e.g. try using java reflection API=)
Checked Exceptions are useful for handling events that occur in the normal operation of a program. An example would be an IOException that is thrown when a file cannot be opened. These exceptions occur even if there is nothing wrong with the program. It is necessary, therefore, to tell the program how to handle the exception.
Unchecked exceptions are useful for identifying defects in the code. For instance, a NullPointerException is thrown when a value is read on a null object. Thus an Unchecked Exception represents a problem that requires a manual fix by the programmer. It is reasonable for the program to crash in order to avoid erroneous behavior, so a try-catch block is not required (but might be desirable in order to provide mitigation, such as displaying an error to the user).
What is your question exactly?
Compilers shouldn't (and won't) enforce you to try/catch unchecked exceptions, that would go against exactly what they are.
The general idea is that checked exceptions are something you may be able to foresee but may be based on input that is out of your control and that you have to deal with.
Unchecked exceptions will usually represent bugs in your program.
There's a number of people that think checked exceptions are a mistake in the Java platform and they only use them very sparingly or not at all. You can read more about this debate by searching google.
It is because,
Unchecked Exceptions are not a result of programmer's fault. Instead they are the serious consequences where we(programmer) aren't expected to do much with it.
In case of Checked Exception, it is an exception generated because of the programmer's fault & often can be resolved by programmer itself.
Check the following links :
Why RunTime Exceptions are unchecked ?
Checked vs Unchecked Exception ?
All Exceptions are part of run time and not compile time. There are two kinds of exceptions checked exceptions and unchecked exceptions. Examples of checked exceptions are IO Exceptions, ClassNotFound Exception and examples of unchecked exceptions are runtime exceptions. In the case of checked exceptions, error or warning message comes at compile time so that the user will take care of it at runtime by using throws keyword, which is used to throw exceptions to the default catch mechanism system. But in case of unchecked exceptions warning is not there at compile time.
**Checked Exceptions
Exceptions which are to be checked or handled or should be taken care during the time of writing the code are called as checked exceptions.
For eg:
1. we have FileNotFoundException -->which will be occured when we are writing some code related to file classes. There will e defenetly posibility of non existence of file. In such case in order to handle them , we are forced to handle those exception for sure.
2. one more example is ParseException ,which will be occured when we are dealing with date functions.
UnChecked Exceptions
These are the exceptions that are optional to be handled during the time of coding. Its up to us whether we handle them or not. In case if we fail to handle them, There is a chance of getting runtime errors during the exceution.
For eg:
We have something called NullPointerException,ArithemeticException,NosSuchElementFoundException and so on. These are like optional things we dont even have to handle them. More over even jvm or compiler will not recommend us to handle them.**
in simple words,
checked exceptions are those which can be and should be handled by your code(therefore compiler forces you to handle them)
unchecked exceptions are those which lie beyond programmer's control(therefore compiler doesn't forces you to handle them)
use the same rule even while creating your custom exceptions.

What is the criteria of an exception to be tagged as checked or unchecked ?Eg: IllegalArgumentException is unchecked but IOException is not [duplicate]

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.

Runtime exception and Checked exception [closed]

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

Why is catching a RuntimeException not considered a good programming practice? [closed]

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.

Checked vs Unchecked exception

I've studied that: With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
what its mean?
according to that code there is no need to put try catch block in code,
but i've seen compiler forces to put the code in try catch block.
I'm very confused what they are exactly?
Unchecked exceptions are those that extend RuntimeException class. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword. All other exception types (that do not extend RuntimeException) are checked and therefore must be declared to be thrown and/or catched.
Checked exceptions are used when you want the caller of your method (i.e the user of your API) to explicitly handle the exceptional case in your API. Checked exceptions are declared when you believe the call will be able to do something meaningful with that exceptional case, like retrying the call, rolling changes back or converting it into some user-readable error message.
If you believe that there is nothing useful the call can do about the exception (especially when it represents a bug, or a wrong usage of your API), then the exception should be unchecked. Also, an API with too many checked exceptions can be annoying to program with (e.g. try using java reflection API=)
Checked Exceptions are useful for handling events that occur in the normal operation of a program. An example would be an IOException that is thrown when a file cannot be opened. These exceptions occur even if there is nothing wrong with the program. It is necessary, therefore, to tell the program how to handle the exception.
Unchecked exceptions are useful for identifying defects in the code. For instance, a NullPointerException is thrown when a value is read on a null object. Thus an Unchecked Exception represents a problem that requires a manual fix by the programmer. It is reasonable for the program to crash in order to avoid erroneous behavior, so a try-catch block is not required (but might be desirable in order to provide mitigation, such as displaying an error to the user).
What is your question exactly?
Compilers shouldn't (and won't) enforce you to try/catch unchecked exceptions, that would go against exactly what they are.
The general idea is that checked exceptions are something you may be able to foresee but may be based on input that is out of your control and that you have to deal with.
Unchecked exceptions will usually represent bugs in your program.
There's a number of people that think checked exceptions are a mistake in the Java platform and they only use them very sparingly or not at all. You can read more about this debate by searching google.
It is because,
Unchecked Exceptions are not a result of programmer's fault. Instead they are the serious consequences where we(programmer) aren't expected to do much with it.
In case of Checked Exception, it is an exception generated because of the programmer's fault & often can be resolved by programmer itself.
Check the following links :
Why RunTime Exceptions are unchecked ?
Checked vs Unchecked Exception ?
All Exceptions are part of run time and not compile time. There are two kinds of exceptions checked exceptions and unchecked exceptions. Examples of checked exceptions are IO Exceptions, ClassNotFound Exception and examples of unchecked exceptions are runtime exceptions. In the case of checked exceptions, error or warning message comes at compile time so that the user will take care of it at runtime by using throws keyword, which is used to throw exceptions to the default catch mechanism system. But in case of unchecked exceptions warning is not there at compile time.
**Checked Exceptions
Exceptions which are to be checked or handled or should be taken care during the time of writing the code are called as checked exceptions.
For eg:
1. we have FileNotFoundException -->which will be occured when we are writing some code related to file classes. There will e defenetly posibility of non existence of file. In such case in order to handle them , we are forced to handle those exception for sure.
2. one more example is ParseException ,which will be occured when we are dealing with date functions.
UnChecked Exceptions
These are the exceptions that are optional to be handled during the time of coding. Its up to us whether we handle them or not. In case if we fail to handle them, There is a chance of getting runtime errors during the exceution.
For eg:
We have something called NullPointerException,ArithemeticException,NosSuchElementFoundException and so on. These are like optional things we dont even have to handle them. More over even jvm or compiler will not recommend us to handle them.**
in simple words,
checked exceptions are those which can be and should be handled by your code(therefore compiler forces you to handle them)
unchecked exceptions are those which lie beyond programmer's control(therefore compiler doesn't forces you to handle them)
use the same rule even while creating your custom exceptions.

Categories