Why is try/catch needed in some cases but not others? [duplicate] - java

This question already has answers here:
Checked vs Unchecked exception
(7 answers)
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 9 years ago.
I've been doing some pure Java development recently, and I'm using an external lib that exposes a small number of methods, each of which have the possibility of throwing an Exception.
Eclipse won't let me compile my program unless I wrap each of those calls in a try-catch block. So far, no big deal.
Then I noticed some things, like ArrayList.add(), which throws IndexOutOfBoundsException. How is it that I can call something like this without needing to wrap it in a try..catch? Obv, in this particular case, it would be incredibly irritating if you had to do it each time, but how and why is try-catch enforced in some situations, but not others?

Unchecked exceptions (subclasses of Error or RuntimeException) need no try..catch block, and when there is no try...catch, the method need not to declare itself to be throws (you can, of course, and some consider declaring throws to be a good practice) . On the other hand, checked ones do need the try...catch, or declares throws.

IndexOutOfBoundsException is an unchecked exception, i.e. it extends RuntimeException or Error, or sub class of either, therefore a try/catch block is unnecessary. From the docs:
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
In contrast, checked exceptions require a try/catch block otherwise a compiler error will result.

Related

Method overloading and throws exception handling [duplicate]

This question already has answers here:
Should methods that throw RuntimeException indicate it in method signature?
(7 answers)
Closed 4 years ago.
Let's say I have the following code:
public void methodOne(String argumentOne) {
methodOne(argumentOne, false);
}
public void methodOne(String argumentOne, boolean equality) {
//App logic here
}
And if the app logic throws an exception (say IllegalArgumentException/Parse Exception), and i would like to catch this in the caller method, should the "throws IllegalArgumentException" be added in all the method identifier or only on the base method identifier? Is there any advantage over this?
Throwing a checked exception means you expect the caller to be forced to think about how to handle that exception. You should only do this when:
This is a deliberate, desirable action in your mind.
You have some idea how you expect the caller to deal with a checked exception. Ideally, you have documented what you expect them to do with the exception.
Thus it's a very bad idea to
declare "throws" an exception which is never actually thrown. This just causes confusion and get the developer into the habit of ignoring your exceptions as they have no value.
throw a checked exception when it is unlikely to be a reasonable way to recover from it. An unchecked exception might be better in that case.
I prefer to add throws clauses for unchecked exceptions as a form of documenting what can go wrong and what it means without forcing the caller to handle those exceptions.
Additionally, you should try to add meaningful messages to each Exception/Error to make it easier for a developer to work out how to fix the code or configuration.
i would like to catch this in the caller method, should the "throws IllegalArgumentException" be added in all the method identifier or only on the base method identifier?
Only add it to the methods which can actually throw the exception.

When to use "throws RuntimeException" Java [duplicate]

This question already has answers here:
In Java, when should I create a checked exception, and when should it be a runtime exception? [duplicate]
(14 answers)
Closed 4 years ago.
I am doing a code review and I have came across this method definition:
public void something() throws RuntimeException
Is there a rational reason to write 'throws RuntimeException' in Java?
RuntimeException is unchecked exception and therefore can be thrown from any place in the code. Saying "Hey, this method can throw RuntimeException" and knowing that any piece of code can do so may be redundant. The only reason I can think of, you would like to make it explicit is for documentation purposes, eg. "Throws RuntimeException when some specific thing happens", but then it probably belongs to javadoc, not to method signature.
Everything is context-dependent, of which you shared none; but on a general note in may be said that this very rarely makes sense. Methods declare unchecked exceptions for documentation purposes, but these are normally specific exceptions carrying some domain-specific meaning. Declaring to throw a completely generic unchecked exception is thus quite hard to justify, although I cannot say there is absolutely no situation where it may make sense.
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.
This types of exceptions depend directly of code, for example, "ArrayIndexOutOfBoundsException".So, if you don't use arrays, arraylists, casting or something what could throw a RuntimeException, it wouldn't be neccesary to write that.
Any method can throw RuntimeException, like NullPointerException being most common. So if a method throws RuntimeException (or it's subclass), it's usually not put that in method signature.
So according to me, it just shows inmaturity of the programmer as it doesn't add any value. Though, it's not asked but even the method name i.e. something() is fishy. It doesn't convey any meaning to the reader.

java - In java, why is Exception the base class and not RuntimeException? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
The Java specification requires that if an exception is thrown, it is either handled by a try/catch statement, or that the function is declared with "throws XYZException". This has the exception of RuntimeException, where it is OK if this is thrown without being caught.
This might sound like a matter of opinion, but the more I think about it, the more it seems really counter-intuitive:
Why is it that we have a RuntimeException extending Exception?
When I first started doing Java, I thought ALL exceptions had to be caught in that way, and it made sense because all exceptions extend Exception. It seems like a violation of OOP to have a RuntimeException exception exception :P. Since RuntimeException makes throws kinda redundant, why didn't Java allow all exceptions at runtime in the first place, adding a throws only when you want to force the caller to handle that type of exception?
Examples:
void noThrows() {
throw new Exception();
}
... no errors.
void hasThrows() throws AnyBaseOfXYZException {
throw new XYZException();
}
... no errors.
void testFunction() {
hasThrows();
}
... fails since "hasThrows" throws AnyBaseOfXYZException, and this is not handled
void testFunction() {
try {
hasThrows();
} catch (AnyBaseOfXYZException e) {
...
}
}
... no errors.
I'd thought about maybe some kind of "CompileTimeException" that extends Exception, but when you give it enough thought, it just can't work without being as ugly as RuntimeException.
Basically, why did Java decide to force all exceptions to require throws except for RuntimeExceptions, when all exceptions could be runtime exceptions except when otherwise stated with throws?
Firstly, the base class of all things that can be thrown is Throwable (not Exception).
Under Throwable are two subclasses: Exception and Error.
Under Exception is RuntimeException.
Of these 4 main classes, RuntimeException and Error are unchecked (may be thrown without having to be declared as being thrown).
The idea behind RuntimeException being unchecked is that it's typically a programming error and that normal good practice should avoid them (eg ArrayIndexOutOfBoundsException or NullPointerException) and to require them to be caught would clutter up the code massively.
The reason Errors are unchecked is that basically, there's nothing you can to about it if one happens, eg OutOfMemoryError etc.
That leaves all other Throwables, ie subclasses of Exception, must be declared as thrown or caught. The idea behind this is that checked exceptions can be "handled by the caller". eg FileNotFoundException (we know what this means and should know what to do if we get one).
The Java designers didn't always get this right. SQLException is checked, but there's no realistic way to recover - do I have a syntax error in my query? is the database refusing conections? who knows, but I do know I can't "handle" it.
In some cases you want to have a catch that catches all exceptions: checked and unchecked.
Java's design decision allows you to achieve that with catch (Exception e) { ... }
If unchecked exceptions (exceptions that extends RuntimeException) were not extending Exception then you had to use two catch clauses.
This might be related to topic of check and uncheck exception. From RuntimeException
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions
do not need to be declared in a method or constructor's throws clause if they can
be thrown by the execution of the method or constructor and propagate outside the
method or constructor boundary.
Check exception is to be use for case that recoverable when the program is executed. So it makes perfect sense to force programmer writing the class to declare it in a method definition. By doing so the caller will be force to catch it or re throw it.
However uncheck exception is for a case that is unrecoverable and thus it is better to terminate. This case is rarely happen (usually happen when the code is still being developed) and thus this usually indicate a programmer error or a very fatal bug that usually need to fix by the class writer and is not recoverable by the client of the class.

Definition of checked Java exception?

I see that one definition can be this:
Generally RuntimeExceptions are exceptions that can be prevented
programmatically.
But that is still not the definition of a checked exception. I thought checked exceptions were "exceptions that can be handled at compile-time". Is that correct and/or can you tell me more?
I also read this on the site, can you explain the quote?
Many people say that checked exceptions (i.e. these that you should
explicitly catch or rethrow) should not be used at all.
Java: checked vs unchecked exception explanation
Can I just learn what the definition is? I also read somewhat unexpectedly:
NumberFormatException is unchecked`
But I would think that NumberFormatException is checked since I would handle that at compile-time. Can you please help me understand? I've done some Java programming but I never wrote my own exception class, why would I need that?
Update
A definition is given is the SCJP book by Sierra / Bates:
A checked exception is defined as any subclass of java.lang.Throwable (including Throwable itself) which is not a subclass of java.lang.Error or java.lang.RuntimeException. The guidelines you saw are just that, guidelines, designed to help you understand the intent of runtime exceptions.
See the Java Language Specification, section 11.1.1
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.
A more broad definition is:
CheckedExceptions are exceptions that you have to deal with explicitly. You either have to declare you can throw it or catch it and deal with it. Cunningham Wiki
As a result RuntimeExceptions are not checked, but NumberFormatException is checked if a method declares that it throws it and you are forced to catch or re-throw.
Checked exceptions allow you to verify at compile time that you are either handling exceptions or declaring them to be thrown.
Some do suggest avoiding checked exceptions. However, this does not eliminate the cost of managing exceptions. It shifts and magnifies it, from compile-time to run time and debug time.
From the Java tutorial:
[P]rogrammers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
Unchecked exceptions allow you to not have to declare everywhere exceptions that can occur almost anywhere. From the Java tutorial:
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).
NumberFormatException is unchecked because it falls within this camp. In many applications, number format exceptions can occur almost anywhere, and be numerous.

How are exceptions propagated? [duplicate]

This question already has answers here:
Why doesn't Java allow to throw a checked exception from static initialization block?
(8 answers)
Closed 9 years ago.
I want to understand exception propagation in java at thread level.
My understanding is that when ever a code throws an exception and if the method is not handling that exception then it is stored in the stack of that thread and jvm just keeps popping out method calls from stack if exception is not handled. This method will apply to both Checked and unchecked exceptions. Please correct me if i am wrong.
With above explanation i am not able to understand how are exceptions in static block handled because they will be called during class loading time.
Any ideas on this?
Java strictly and precisely defines the moment at which a class is initialized (as opposed to loaded, BTW!). It is always triggered by some Java code, so the particular line of Java code that triggers the class init will receive the exception. There is no magic, no special cases, and it always happens at runtime, just like any other exceptions.
The code inside static block is also executed in a thread (even if it is indeed called at class initialization time) and so the same strategy applies to unchecked exceptions thrown from a static block.
Note that you will get a compilation error if your code throws a checked exception from a static block.

Categories

Resources