Throw nested exception through java Throwable - java

I trying to throw inner exception in another exception through java Throwable but IDE told my that you must surround it with try/cath, What should I do to avoid from this problem?
try
{
//Some code
}
catch (IOException e)
{
Throwable cause = new Throwable();
cause.initCause(e);
throw cause.getCause();
}

Change your method signature to this:
public void someMethod() throws IOException
{
//some code
}
Have a look at this site for some useful information on checked exceptions and a little on the difference between checked and unchecked exceptions

Declare IOException as a checked exception in your function's signature.

Related

Difference between throw and throws in finally

I am preparing for OCP exam and I'm using Enthuware.
I got this question, what is the result of compiling and running the following code?
try {
throw new IOException();
} catch(IOException e) {
throw e;
} finally {
throw new RuntimeException();
}
Obviously, the code does compile but it throws a RuntimeException and I totally understand why.
I'm just curious why the following code doesn't compile:
try {
throw new IOException();
} catch(IOException e) {
throw e;
} finally {
test();
}
Where test() function looks like:
static final void test() throws RuntimeException {
throw new RuntimeException();
}
Even though I declared test function as final because I thought that it might the compiler is aware of overriding ...
Could someone please explain it to me?
Sorry for bad English!
-- Edit:
Just wondering why down-vote?
Error message is compile error:
Unhandled exception type IOException
And the error message when I tried to compile it is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
The first snippet compiles because the finally block runs before a value is returned or an exception thrown from the non-finally part of the method. The fact that you're throwing a RuntimeException means that you won't be throwing the IOException that you otherwise would. The compiler can work this out, and it therefore doesn't insist that you either declare or catch the IOException.
But the compiler only looks at one method at a time when it's performing this check. So the second snippet fails to compile, because the compiler doesn't check whether test() will always throw the RuntimeException. Instead, it assumes that test() might not throw the RuntimeException; and if that were to happen, the IOException would be thrown. Therefore, the compiler insists that you either catch that IOException, or declare it in a throws clause.
In java Exception handling have concept Exception propagation.
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, if not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.
Rule 1: By default, Unchecked Exceptions are forwarded in calling chain (propagated).
Rule 2: By default, Checked Exceptions are not forwarded in calling chain (propagated).
try {
throw new IOException();
} catch(IOException e) {
throw e;
} finally {
throw new RuntimeException();
}
In above code snippet it's the throwing of the RuntimeException that prevents the throwing of the IOException.
try {
throw new IOException();
} catch(IOException e) {
throw e;
} finally {
test();
}
static final void test() throws RuntimeException {
throw new RuntimeException();
}
In above code snippet test() method throwing of the RuntimeException but not prevents the throwing of the IOException.
As by Rule 2 by default compiler doesn't propagate the Checked Exceptions so for that you have to declare or handle the exception.
Lets take example if you replace IOException with RuntimeException then it will not give compiletime error because by Rule 1 by default unchecked Exceptions are forwarded in calling chain (propagated).
try {
throw new RuntimeException();
} catch(RuntimeException e) {
throw e;
} finally {
test();
}
static final void test() throws RuntimeException{
throw new RuntimeException();
}

Signature Declare Throws Exception : A method/constructor shouldn't explicitly throw java.lang.Exception

I got this warning on sonar. what is the proper solution to this warning.
My methos is Like:
public void abc(A a) throws Exeption {
dao.pqr(a);
}
i got warning to this method in Class.What is proper solution to this?
You should throw the actual Exception(s) if they are known.
If the method you call throws Exception and you can't change it there is nothing you can do about it except suppress the warning.
A method can only throw the exceptions that are relevant to its interface. Exception is the "root" of all exception, so try to be more specific.
You can catch the exception and reconvert it to a Particular exception.
protected RunningJob submitJob(Configuration actionConf) throws RuntimeException {
.....
RunningJob rj;
try{
rj = super.submitJob(actionConf);
}catch(Exception e){
throw new RuntimeException(e);
}
return rj;
}
If you throw Exception, it is unclear as which exceptions the method can throw as Exception is very generic.

"unhandled checked exception as a thrown exception" in Java

I'm learning chapter 5 of SCJP 6 Study Guide Exam_310-065 and in section Exception Declaration and the Public Interface it says
"Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown
exception."
How do we list each unhandled checked exception as a thrown exception and how does it look like in the code? Thanks.
It looks like this:
public void foo() throws SomeCheckedException, AnotherCheckedException
{
// This method would declare it in *its* throws clause
methodWhichThrowsSomeCheckedException();
if (someCondition)
{
// This time we're throwing the exception directly
throw new AnotherCheckedException();
}
}
See section 8.4.6 in the JLS for more information.
For instance, if you have:
public void doSomething() throws SomeException {
...
throw new SomeException();
}
And you want to invoke doSomething, you've got to either catch the exception, or declare the method using it as also susceptible of throwing SomeException, therefore propagating it further in the call stack:
public void doSomethingElse() throws SomeException {
doSomething();
}
Or
public void doSomethingElse() {
try {
doSomething();
}
catch (SomeException) {
// Error handling
}
}
Take into account that RuntimeExceptions are not checked exceptions, so they are an exception to this rule.

Why try/catch around throwable?

In trying to refactor some I code I attempted to throw the exception in the catch clause like so -
try {
....
}
catch(Exception exception){
.....
throw exception
}
However when I attempted to throw the exception on line "throw exception" the compiler complained with a message that I needed to surround my throw clause in a new try/catch like so -
try
{
....
}
catch (Exception exception)
{
.....
try
{
throw exception
}
catch (Exception e2)
{
...
}
}
Why does the compiler require this and what use does it provide ?
Thanks
The exception java.lang.Exception is a checked exception. This means that it must either be declared in the throws clause of the enclosing method or caught and handled withing the method body.
However, what you are doing in your "fixed" version is to catch the exception, rethrow it and then immediately catch it again. That doesn't make much sense.
Without seeing the real code, it is not clear what the real solution should be, but I expect that the problem is in the original try { ... } catch handler:
If possible, you should catch a more specific exception at that point, so that when you rethrow it, it is covered by the method's existing throws list.
Alternatively, you could wrap the exception in an unchecked exception and throw that instead.
As a last resort, you could change the signature of the method to include Exception in the throws list. But that's a really bad idea, because it just pushes the problem off to the caller ... and leaves the developer / reader in the position of not knowing what exceptions to expect.
In Java, there is a distinction between checked and unchecked exceptions. An unchecked exception can essentially be thrown at any place in code and, if it's not caught somewhere, it will propagate up to the entry point of your application and then stop the process (usually with an error message and stack trace). A checked exception is different: The compiler won't let you just let it propagate, you need to either surround any code which might throw a checked exception with try-catch blocks (and "throw exception" is the simplest case if exception is an instance of a checked exception class) or you must mark the method which contains the call to code that might throw a checked exception with a "throws" declaration. If the desired behaviour is to throw an unchecked exception, then you'll need to wrap the exception in a RuntimeException. If the desired behaviour is to keep the exception checked, then you'll need to add a throws declaration to your current method.
In your original code, nothing catches the thrown exception. I would imagine you either have to specify that your function throws an exception or have another try/catch block as the compiler suggests to catch it.
Instead of
public void yourFunction(){
try {
....
}
catch(Exception exception){
.....
throw exception
}
}
try
public void yourFunction() throws Exception{
try {
....
}
catch(Exception exception){
.....
throw exception
}
}
My guess is that your trying to throw an exception sub class that isn't declared by the method as an exception type it can throw.
The following example works
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws Exception{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
However this example will give an error.
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
Note in the second example I'm simply catching Exception not RuntimeException, it won't compile as I throw Exception which is an undeclared throws, even though I do declare RuntimeException.
Yes the exception is a RuntimeException but the compiler doesn't know that.
Just thought of a third working example to show you. This one also works because your throwing the same type as you declare. (note the only change is the catch block)
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (RuntimeException e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
You need to understand the differences between all three of these answers

Magic Exception thrower without declaring throws Exception

I want a method that can throw any Throwable including sub classes of Exception. Ive got something that takes an exception, stashes it in a thread local, then invokes a class.newInstance. That class ctor declares that it throws Exception then takes the threadlocal and throws it. Problem is it does not work for the two declared Exceptions thrown by Class.newInstance() namely IllegalAccessException and InstantiationException.
Im guessing any other method using some sun.* class is just a hack and not really reliable.
Wrapping is not an option because that means catchers are catching a diff type and that's just too simple and boring...
static public void impossibleThrow(final Throwable throwable) {
Null.not(throwable, "throwable");
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
}
if (throwable instanceof Error) {
throw (Error) throwable;
}
try {
THROW.set((Exception) throwable);
THROWER.newInstance();
} catch (final InstantiationException screwed) {
throw new Error(screwed);
} catch (final IllegalAccessException screwed) {
throw new Error(screwed);
} finally {
THROW.remove();
}
}
private final static Class<Impossible> THROWER = Impossible.class;
private final static ThreadLocal<Exception> THROW = new ThreadLocal<Exception>();
static private class Impossible {
#SuppressWarnings("unused")
public Impossible() throws Exception {
throw THROW.get();
}
}
From Java Puzzlers (puzzle 43):
public static void impossibleThrow(Throwable t)
{
Thread.currentThread().stop(t); // Deprecated method.
}
The book shows other methods of achieving the same problem, one is a simplified version of yours, the other exploits generic type erasure to throw any Throwable where an Error is expected.
If you want an Exception to bubble up through code not expecting that exception then just wrap it in a RuntimeException
} catch (RuntimeException e) {
throw e; // only wrap if needed
} catch (Exception e) {
throw new RuntimeException("FOO went wrong", e);
}
Remember to let the message be informative. Some day you will have to fix a bug based only on the information in the stack trace.
Wrapping an exception inside a RuntimeException (as suggested by Thorbjørn) is the way to go. However, you usually want to maintain the stacktrace of the original excpetion. Here's how:
public static void rethrow(final Throwable t)
{
if(t instanceof RuntimeException)
throw (RuntimeException) t;
RuntimeException e = new RuntimeException(t);
e.setStackTrace(t.getStackTrace());
throw e;
}
I patched javac to remove the error, compiled impossibleThrow(), renamed the source file to something that does not end in .java (which forces the next compile to use the existing .class) and used that.
There is some validity for this question as a debugging tool. Suppose you are working with some code that may have failed and you see that it (perhaps) catches certain exceptions and (perhaps) throws certain exceptions. You suspect that an unexpected exception was not caught. However, the underlying code/system is too complex and the bug is too intermittent to allow you to step through in the debugger. It can be usefull to add the throwing of an exception without changing the method in any other way. In this case, wrapping the exception with a RuntimeException would not work, because you want the calling methods to behave normally.

Categories

Resources