I have a generic function which does something and, in case of failure, it should throw a specific exception.
To simplify you can imagine it as such:
public static <E extends Exception> void doSomething(Class<E> exceptionClass) throws E {
try {
//Do stuff
} catch (Exception e) {
String message = "...";
//-> here I want to throw a new exception of type E with the message I built above and the caught exception as cause
}
}
In order to do that, what I can think about is to build a new E by reflection and throw an unchecked exception if any of the exceptions that can be thrown during reflection is actually thrown:
public static <E extends Exception> buildException(Class<E> exceptionClass, String msg, Throwable cause) {
try {
return exceptionClass.getDeclaredConstructor(String.class, Throwable.class).newInstance(msg, cause);
} catch (NoSuchMethodException ... e) {
//Catch everything that can be thrown
throw new RuntimeException(e);
}
}
... and then call it simply throw buildException(exceptionClass, message, e) inside the main function.
However I don't like too much this solution because I need to get the class in parameter from the caller (while they are already inferring me the type via E) and I may as well have to throw a Runtime exception if my reflection operation fails (all E extends Exception so the constructor I look for should always be there, but we never know if the caller doesn't customize the exception too much...)
Although the drawbacks, I can't get anything better into my mind.
Does anyone have some better design ideas for this?
Note: about the need. I have several classes which perform the same operation (the "do stuff") but that need to throw a specific exception (class 1 throws exception 1, class 2 throws exception 2 etc.) which wraps any possible exception thrown while performing the "do stuff" operation. Of course I may move the catch on caller side but that would make a lot of code duplication for the exact same operation.
Instead of passing the class and let the called method handle the exception creation you could let the calling method handle it instead. This is possible by accepting a function:
public static <E extends Exception> void doSomething(Function<String, E> exceptionFunction) throws E {
try {
//Do stuff
} catch (Exception e) {
String message = "...";
throw exceptionFunction.apply(message);
}
}
This function would expect a String, your message, and will then return an instance of the exception to be thrown. As you can see, you can trigger the function by using exceptionFunction.apply(message).
You can also use e to add the "cause" stacktrace:
public static <E extends Exception> void doSomething(Function<String, E> exceptionFunction) throws E {
try {
//Do stuff
} catch (Exception e) {
String message = "...";
var exception = exceptionFunction.apply(message);
exception.initCause(e);
throw exception;
}
}
The call of the doSomething method would then look like this:
doSomething((s) -> new MyException());
or if you prefer method references, like this:
doSomething(MyException::new);
(mind that MyException would need a constructor with a String parameter)
#Override
Public class example {
void test {
try {
someMethod(); //This throws TimeoutException
} catch (TimeoutException ex) {
throw new TimeoutException(ex); //It doesn't throw error if I replace this with throw new RuntimeException(ex)
} }
}
The above example gives an error as 'throw new TimeoutException(ex)' as "TimeoutException(java.lang.string) in java.util.concurrent.TimeoutException cannot be applied to (java.util.concurrent.TimeoutException)".
But it doesn't throw an error if I replace it with 'throw new RuntimeException(ex)';
TimeoutException doesn't have a constructor that accepts a TimeoutException as an argument of the form TimeoutException(TimeoutException cause) or similar.
You can instead:
TimeoutException localtoe=new TimeoutException("test failed");
localtoe.initCause(ex);
throw localtoe;
Or equally:
throw new TimeoutException("test failed").initCause(ex);
initCause() may only be called once and only if cause wasn't set by a constructor. It's a funny little method that acts like a constructor after-thought(*).
There's nothing necessarily wrong with wrapping an exception as the cause of an exception.
Suppose testFunction() connects and then performs some operation.
You might want to throw an exception with message "connection failed in testFunction" and another "operation failed in testFunction" depending on what sub-step failed.
But if you don't need to provide so much detail you can just throw ex or let the method unwind without itself catching anything.
Here's a little example:
import java.util.concurrent.TimeoutException;
class Example{
private static void connect() throws TimeoutException {
//Dummy connection that just fails...
throw new TimeoutException("connection failed");
}
private static void process() throws TimeoutException {
try {
connect();
}catch(TimeoutException toe){
TimeoutException toeout=new TimeoutException("process failed because connection failed.");
toeout.initCause(toe);
throw toeout;
}
//Code for when connection succeeds...
}
public static void main (String[] args) throws java.lang.Exception
{
try{
process();
}catch(TimeoutException toe){
System.out.println(toe);
}
}
}
Expected output:
java.util.concurrent.TimeoutException: process failed because connection failed.
(*) initCause() looks like an after-thought and is somewhat. It was added to Java 1.4 in 2002. The documentation talks about 'legacy' constructors. Rather than double up the number of constuctors (to add one with a Throwable cause argument) it appears it was decided to allow this as bolt-on initialization.
It's debatable whether that was the best solution.
Things I observed in your question
you are trying to call a method directly from class in a try cache block. which is wrong you have to create method and call it from that
you want to throw an exception. SO you have to throw it method level from where you are calling it
please find the demo solution below :
public class example {
public void testFunction() throws TimeoutException {
try {
someFunction();
} catch (TimeoutException ex) {
throw ex;
}
}
public void someFunction() throws TimeoutException {
}
}
Java has 2 categories of exceptions: checked and unchecked. Checked exception (usually subclasses of Exception) must be declared in function signatures, while unchecked ones (usually subclasses of RuntimeException) must not.
TimeoutException is a checked exception. When it could be thrown from a method that does not declare it, you have 2 options:
declare it in the signature:
public void func1() throws TimeoutException {
somefunction();
}
clean and simple but it can be problemetic is func1 is an override of a function not declared to throw this exception, of it it is called from another function (suppose from a framework) that does not declare it either
hide it in an unchecked exception
public void func1() {
try {
somefunction();
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
you lose the declarative part (checked exceptions exist for that reason), but at least it allows you to call it from function not declaring it.
You have roughly three options here:
Rethrow the same exception: `throw ex;'
Throw a new TimeoutException and lose the stack trace: throw new TimeoutException(ex.getMessage());
Throw an exception of another type, such as RuntimeException.
Each of these options have advantages and drawbacks, you decide.
UPDATE (thanks to #Mark Rottenveel)
Point 2 could be rewritten: throw new TimeoutException(ex.getMessage()).initCause(ex); to keep the link to the original exception.
I am trying to understand exception handling in Java and i keep running into variations of the below mentioned confusing statement in several articles -
There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
This is from http://javarevisited.blogspot.com/2014/02/why-catching-throwable-or-error-is-bad.html#ixzz4hQPkFktf
However, this code compiles -
class CatchThrowable
{
void function()
{
try
{
throw new Throwable();
}
catch (Throwable t)
{
}
}
public static void main(String[] args)
{
try
{
}
catch (Throwable t)
{
}
}
}
Both main and function are able to catch Throwable without declaring that they throw it. My understanding is that the throws keyword is used to declare the checked exceptions which a function throws, not those which it catches. Please clarify the quoted statement.
The statement:
order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
is basically wrong.
You just have to understand the following. There is a exception Hierarchy
A method can throw all types of exception, it just depends on your needs which one you catch and which one not.
It is also not a good idea to catch Error (which includes that you should also not catch Throwable) because there are some severe JMV-VirtualMachineError's like OutOfMemoryError which you usually not should catch.
But this has nothing to do which the fact, what a method declares in its throws part.
This is my array implementation of stack code:
public class ArrayStack2{
private final int DEFAULT_SIZE=10;
public int tos;
Object[] array;
public ArrayStack2(){
array =new Object[DEFAULT_SIZE];
tos=-1;
}
public void push(Object e){
try{
array[tos+1]=e;
tos++;
}
catch(OverFlowException e1){
e1.print();
}
}
and this is OverFlowException class:
public class OverFlowException extends Exception{
public OverFlowException(){
super();
}
public OverFlowException(String s){
super(s);
}
public void print(){
System.out.println("OverFlow");
}
}
When I run this compiler gives the error "exception OverFlowException is never thrown in body of corresponding try statement "
then I realized I have not included the part to check if the array isFull().
My question is I have isFull() method in ArrayStack2 class and how can i call it from OverFlowException class.
Please help me to find a way to correct this exception problem
User defined exception is unchecked exception only if it extends RuntimeException.
In your case it OverFlowException is a checked exception and compiler checks for its possibilities. If there is no possibilities of throwing this checked exception then there is no meaning of handling a checked exception and compiler threat it as Unreachable catch block.
In JAVA anything that is not reachable will result in compile time error.
Try with this sample code for well known checked exception
try {
System.out.println("hello");
} catch (IOException e) {
e.printStackTrace();
}
Compile time error:
Unreachable catch block for IOException.
This exception is never thrown from the try statement body
For more info have a look at User defined exception are checked or unchecked exceptions
My question is I have isFull() method in ArrayStack2 class and how can i call it from OverFlowException class.
Do it in reverse order means throw a new object of OverFlowException class from isFull() method in ArrayStack2 class based on your condition.
Do what the error says to do. That exception can never be caught because it has no possibility to be thrown. You need to throw it if something bad happens:
try{
array[tos+1]=e;
tos++;
if (thereWasAnOverflow) // or however you want to test it. isFull() maybe
throw new OverFlowException();
}
catch(OverFlowException e1){
e1.print();
}
Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?
Thoughts that came to mind are using for example interceptors or aspect-oriented programming.
I haven't tried this, so I don't know if the JVM would restrict something like this, but maybe you could compile code which throws ChuckNorrisException, but at runtime provide a class definition of ChuckNorrisException which does not extend Throwable.
UPDATE:
It doesn't work. It generates a verifier error:
Exception in thread "main" java.lang.VerifyError: (class: TestThrow, method: ma\
in signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestThrow. Program will exit.
UPDATE 2:
Actually, you can get this to work if you disable the byte code verifier! (-Xverify:none)
UPDATE 3:
For those following from home, here is the full script:
Create the following classes:
public class ChuckNorrisException
extends RuntimeException // <- Comment out this line on second compilation
{
public ChuckNorrisException() { }
}
public class TestVillain {
public static void main(String[] args) {
try {
throw new ChuckNorrisException();
}
catch(Throwable t) {
System.out.println("Gotcha!");
}
finally {
System.out.println("The end.");
}
}
}
Compile classes:
javac -cp . TestVillain.java ChuckNorrisException.java
Run:
java -cp . TestVillain
Gotcha!
The end.
Comment out "extends RuntimeException" and recompile ChuckNorrisException.java only :
javac -cp . ChuckNorrisException.java
Run:
java -cp . TestVillain
Exception in thread "main" java.lang.VerifyError: (class: TestVillain, method: main signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestVillain. Program will exit.
Run without verification:
java -Xverify:none -cp . TestVillain
The end.
Exception in thread "main"
After having pondered this, I have successfully created an uncatchable exception. I chose to name it JulesWinnfield, however, rather than Chuck, because it is one mushroom-cloud-laying-mother-exception. Furthermore, it might not be exactly what you had in mind, but it certainly can't be caught. Observe:
public static class JulesWinnfield extends Exception
{
JulesWinnfield()
{
System.err.println("Say 'What' again! I dare you! I double dare you!");
System.exit(25-17); // And you shall know I am the LORD
}
}
public static void main(String[] args)
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
System.out.println("There's a word for that Jules - a bum");
}
}
Et voila! Uncaught exception.
Output:
run:
Say 'What' again! I dare you! I double dare you!
Java Result: 8
BUILD SUCCESSFUL (total time: 0 seconds)
When I have a little more time, I'll see if I can't come up with something else, as well.
Also, check this out:
public static class JulesWinnfield extends Exception
{
JulesWinnfield() throws JulesWinnfield, VincentVega
{
throw new VincentVega();
}
}
public static class VincentVega extends Exception
{
VincentVega() throws JulesWinnfield, VincentVega
{
throw new JulesWinnfield();
}
}
public static void main(String[] args) throws VincentVega
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
}
catch(VincentVega vv)
{
}
}
Causes a stack overflow - again, exceptions remain uncaught.
With such an exception it would obviously be mandatory to use a System.exit(Integer.MIN_VALUE); from the constructor because this is what would happen if you threw such an exception ;)
Any code can catch Throwable. So no, whatever exception you create is going to be a subclass of Throwable and will be subject to being caught.
public class ChuckNorrisException extends Exception {
public ChuckNorrisException() {
System.exit(1);
}
}
(Granted, technically this exception is never actually thrown, but a proper ChuckNorrisException can't be thrown -- it throws you first.)
Any exception you throw has to extend Throwable, so it can be always caught. So answer is no.
If you want to make it difficult to handle, you can override methods getCause(), getMessage(), getStackTrace(), toString() to throw another java.lang.ChuckNorrisException.
My answer is based on #jtahlborn's idea, but it's a fully working Java program, that can be packaged into a JAR file and even deployed to your favorite application server as a part of a web application.
First of all, let's define ChuckNorrisException class so that it doesn't crash JVM from the beginning (Chuck really loves crashing JVMs BTW :)
package chuck;
import java.io.PrintStream;
import java.io.PrintWriter;
public class ChuckNorrisException extends Exception {
public ChuckNorrisException() {
}
#Override
public Throwable getCause() {
return null;
}
#Override
public String getMessage() {
return toString();
}
#Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
}
#Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
}
}
Now goes Expendables class to construct it:
package chuck;
import javassist.*;
public class Expendables {
private static Class clz;
public static ChuckNorrisException getChuck() {
try {
if (clz == null) {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("chuck.ChuckNorrisException");
cc.setSuperclass(pool.get("java.lang.Object"));
clz = cc.toClass();
}
return (ChuckNorrisException)clz.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
And finally the Main class to kick some butt:
package chuck;
public class Main {
public void roundhouseKick() throws Exception {
throw Expendables.getChuck();
}
public void foo() {
try {
roundhouseKick();
} catch (Throwable ex) {
System.out.println("Caught " + ex.toString());
}
}
public static void main(String[] args) {
try {
System.out.println("before");
new Main().foo();
System.out.println("after");
} finally {
System.out.println("finally");
}
}
}
Compile and run it with following command:
java -Xverify:none -cp .:<path_to_javassist-3.9.0.GA.jar> chuck.Main
You will get following output:
before
finally
No surprise - it's a roundhouse kick after all :)
In the constructor you could start a thread which repeatedly calls originalThread.stop (ChuckNorisException.this)
The thread could catch the exception repeatedly but would keep throwing it until it dies.
No. All exceptions in Java must subclass java.lang.Throwable, and although it may not be good practice, you can catch every type of exception like so:
try {
//Stuff
} catch ( Throwable T ){
//Doesn't matter what it was, I caught it.
}
See the java.lang.Throwable documentation for more information.
If you're trying to avoid checked exceptions (ones that must be explicitly handled) then you will want to subclass Error, or RuntimeException.
Actually the accepted answer is not so nice because Java needs to be run without verification, i.e. the code would not work under normal circumstances.
AspectJ to the rescue for the real solution!
Exception class:
package de.scrum_master.app;
public class ChuckNorrisException extends RuntimeException {
public ChuckNorrisException(String message) {
super(message);
}
}
Aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.ChuckNorrisException;
public aspect ChuckNorrisAspect {
before(ChuckNorrisException chuck) : handler(*) && args(chuck) {
System.out.println("Somebody is trying to catch Chuck Norris - LOL!");
throw chuck;
}
}
Sample application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
catchAllMethod();
}
private static void catchAllMethod() {
try {
exceptionThrowingMethod();
}
catch (Throwable t) {
System.out.println("Gotcha, " + t.getClass().getSimpleName() + "!");
}
}
private static void exceptionThrowingMethod() {
throw new ChuckNorrisException("Catch me if you can!");
}
}
Output:
Somebody is trying to catch Chuck Norris - LOL!
Exception in thread "main" de.scrum_master.app.ChuckNorrisException: Catch me if you can!
at de.scrum_master.app.Application.exceptionThrowingMethod(Application.java:18)
at de.scrum_master.app.Application.catchAllMethod(Application.java:10)
at de.scrum_master.app.Application.main(Application.java:5)
A variant on the theme is the surprising fact that you can throw undeclared checked exceptions from Java code. Since it is not declared in the methods signature, the compiler won't let you catch the exception itself, though you can catch it as java.lang.Exception.
Here's a helper class that lets you throw anything, declared or not:
public class SneakyThrow {
public static RuntimeException sneak(Throwable t) {
throw SneakyThrow.<RuntimeException> throwGivenThrowable(t);
}
private static <T extends Throwable> RuntimeException throwGivenThrowable(Throwable t) throws T {
throw (T) t;
}
}
Now throw SneakyThrow.sneak(new ChuckNorrisException()); does throw a ChuckNorrisException, but the compiler complains in
try {
throw SneakyThrow.sneak(new ChuckNorrisException());
} catch (ChuckNorrisException e) {
}
about catching an exception that is not thrown if ChuckNorrisException is a checked exception.
The only ChuckNorrisExceptions in Java should be OutOfMemoryError and StackOverflowError.
You can actually "catch" them in the means that a catch(OutOfMemoryError ex) will execute in case the exception is thrown, but that block will automatically rethrow the exception to the caller.
I don't think that public class ChuckNorrisError extends Error does the trick but you could give it a try. I found no documentation about extending Error
Is it possible to construct a snippet of code in java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?
Yes, and here's the answer: Design your java.lang.ChuckNorrisException such that it is not an instance of java.lang.Throwable. Why? An unthrowable object is uncatchable by definition because you can never catch something that can never be thrown.
You can keep ChuckNorris internal or private and encapsulate him or swollow him...
try { doChuckAction(); } catch(ChuckNorrisException cne) { /*do something else*/ }
Two fundamental problems with exception handling in Java are that it uses the type of an exception to indicate whether action should be taken based upon it, and that anything which takes action based upon an exception (i.e. "catch"es it) is presumed to resolve the underlying condition. It would be useful to have a means by which an exception object could decide which handlers should execute, and whether the handlers that have executed so far have cleaned things up enough for the present method to satisfy its exit conditions. While this could be used to make "uncatchable" exceptions, two bigger uses would be to (1) make exceptions which will only be considered handled when they're caught by code that actually knows how to deal with them, and (2) allow for sensible handling of exceptions which occur in a finally block (if a FooException during a finally block during the unwinding of a BarException, both exceptions should propagate up the call stack; both should be catchable, but unwinding should continue until both have been caught). Unfortunately, I don't think there would be any way to make existing exception-handling code work that way without breaking things.
It is easily possible to simulate a uncaught exception on the current thread. This will trigger the regular behavior of an uncaught exception, and thus gets the job done semantically. It will, however, not necessarily stop the current thread's execution, as no exception is actually thrown.
Throwable exception = /* ... */;
Thread currentThread = Thread.currentThread();
Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
currentThread.getUncaughtExceptionHandler();
uncaughtExceptionHandler.uncaughtException(currentThread, exception);
// May be reachable, depending on the uncaught exception handler.
This is actually useful in (very rare) situations, for example when proper Error handling is required, but the method is invoked from a framework catching (and discarding) any Throwable.
Call System.exit(1) in the finalize, and just throw a copy of the exception from all the other methods, so that the program will exit.