0

I am trying to catch an exception, and then throw it.

try{
    arr = new class[arrLen]; //Goes to a constructor that may cause an exception
}
catch(Exception e){
    MyException e = new MyException;
    throw e;
}

As you can see, I am trying to execute a command, and then if it causes an exception, I want to create a new instance of MyException and then throw it.

What I am having problems with is whether I am supposed to create the "Exception e" and then try and create a new "MyException e", or am I supposed to make a new MyException, AKA

MyException f = new MyException;
throw f;
5
  • 1
    Please use proper syntax in your code examples. Commented Dec 4, 2013 at 0:01
  • 1
    I'd say that it's weird to reuse e. Just a feeling. Commented Dec 4, 2013 at 0:04
  • What's wrong with the syntax? I'm still pretty new to this community Commented Dec 4, 2013 at 0:08
  • Why do you want to catch and throw it? A catch and throw pattern makes not much sense in most cases but you can certainly do that. - "catch an exception, and then throw it" would be when you don't create a new one. You can also catch one exception then throw a different one. Or just catch it without throwing. Or not catch it at all and let other code handle it. Commented Dec 4, 2013 at 0:11
  • @bob your syntax is incorrect and won't compile. There are several problems, and you should make sure the code compiles before pasting it into a question. Commented Dec 4, 2013 at 0:14

1 Answer 1

1

You should create a new MyException with a new variable, like f. This new exception should use the original Exception as the cause. For example

MyException f = new MyException(e);
throw f;

Or you can reuse the e variable if MyException extends Exception.

e = new MyException(e);
throw e;
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Worked perfectly :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.