How are exceptions propagated? [duplicate] - java

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.

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.

Java 8 orElseThrow: why is compiler not complaining that method does not have a "throws" [duplicate]

This question already has answers here:
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 4 years ago.
I have the following code:
public Trail getNewestTrail() {
return trails.stream().max(Comparator.comparing(Trail::getTimestamp)).orElseThrow(NoSuchElementException::new);
}
I am not seeing any error without having getNewestTrail declared as throwing the exception -- why?
NoSuchElementException extends from java.lang.RuntimeException, it is uncheched exception:
Java programming language does not require methods to catch or to
specify unchecked exceptions (RuntimeException, Error, and their
subclasses)
you only need specify checked exception in method signature.
NoSuchElementException is a RuntimeException and they need not be handled at compile time.
Just to check, replace NoSuchElementException with Exception and it will start giving you a compilation failure.

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

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.

Why can you not throw and catch an Object in Java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What can you throw in Java?
Why can't I take an Exception in a reference of Object.
I mean consider the following code:
try{.......}
catch(Object ex){.......}
It shows an error, where as we knows that it's possible for all the objects of any class to be referenced by Object.
The Java Language specification says that only Throwables can be thrown.
http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#44043
Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it.
The language could have been defined differently, but Java tends to define a base type for any kind of thing that is intended to be used in a particular way and defines methods in that base class to support common patterns. Throwable in particular supports chaining and stack trace printing. It would not be possible to chain exceptions as easily if the only thing you knew about an exception was that it was a reference type.
You can assign a reference of an Exception to an Object without a problem. But Objects can't be thrown or catched.
That only works for Throwables.
So that in catch block you can be sure to get some details on exception like getCause(), getMessage(), getStackTrace(). If its generic Object, you wont have access to these methods without explicit casting, and you wont be still sure that these method actually exist. As its instance of Throwable, you are sure that you can retrieve these details from exception (the object in the catch).
You can't because only subclasses of Throwable can be thrown. I suppose it would be possible for them to have allowed you to use Object in a catch block, instead -- the only superclass of Throwable -- but what would be the point, since the variable would always refer to a Throwable instance.
Maybe you are coming from C++ where anything can be thrown, even an int. Java exceptions extend Throwable. Object does not extend it (of course).

Error class in Java

I am trying to understand the Error class in Java.
I have a good understanding of the Exception class, but can't find examples of code for the Error class. I've tried searching the web and also the java.sun website, but I'm not finding anything useful to help me understand this better.
How do I use the Error class in programs and where do we have to use that?
You don't use Error in your code.
An Error is a specific kind of Throwable, just as Exception is.
Throwable is the base class that defines everything that can be thrown.
Exception is the common case. It is about problems that occur during the execution of your program.
RuntimeException is a special case: it's unchecked (i.e. it need not be declared by a method and the compiler doesn't force you to catch it).
Error is the "rare" case: it signifies problems that are outside the control of the usual application: JVM errors, out of memory, problems verifying bytecode: these are things that you should not handle because if they occur things are already so bad that your code is unlikely to be able to handle it sanely.
You should not attempt to correct the situation that resulted in an Error. You might want to catch it in order to log it and then rethrow it (see the JavaDoc of ThreadDeath for an example on why you need to rethrow it (thanks to #krock for the heads-up)).
There is no other reason to throw any Error (i.e. don't create an Error on your own and throw it, if you think you want to do that, use an Exception or a RuntimeException instead).
If you take a look at the Javadoc here there is a good explanation:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
Concerning the usage you also have this:
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
Error
Error a subclass of "Throwable" class is thrown by java runtime system and indicate some unrecoverable conditions during the execution of the programs
Once thrown difficult to recover from it and the application get to halt.
Eg..,java.lang.StackOverflowError and java.lang.OutofMemoryError
// An example code which throws StackOverflowError
public class ErrorDemo
{
public void method1()
{
this.method2();
}
public void method2()
{
this.method1();
}
public static void main(String sri[])
{
ErrorDemo k= new ErrorDemo();
k.method1();
}
}
In this code from main method we are calling method1 and from method1 a call was made to method2 and again from method2 we are calling method1 means we created a continous loop which doesn't goes to end and finally a critical error StackOverflowError is being thrown.

Categories

Resources