1

I have following exception

public class MyException extends SecurityException{
      public MyException( String s ) { super( s ) ; }
}

where SecurityException is java.lang.SecurityException.

whenever I throw MyException("Message");, I can get the message.

Now, in MyException I want to pass an integer value with MyException and access that integer where I am catching this MyException.

How do I do that ?

2
  • 4
    Exception classes aren't some mystical voodoo magic - they're objects just like anything else. Do it in the same way that you would do it for any other type of object. Commented Dec 2, 2016 at 12:22
  • Ohh yes @JonK I had not seen any such exceptions so I was assuming it would be difficult. Thanks, next time I would approach problems in that easy way mindset. Commented Dec 5, 2016 at 5:55

2 Answers 2

7
public class MyException extends SecurityException{
  private int i;
  public MyException(String s, int i) { 
     super(s);
     this.i = i;
  }

  public int getI() { return i; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have this catch(Exception e) where e would be MyException but now if i see i can only have java.lang.Exception's methods not getValue()
If you want to pass values within your exception, then in your code you should catch your own exception.
1

You can specify a member variable in MyException class and use it at catch point. Something like -

public class MyException extends SecurityException{
  private Integer value;
  public MyException( Integer n, String s ) { 
       super(s) ;
       value = n;
  }
  public Integer getValue() {
       return value;
  }
}

2 Comments

I have this catch(Exception e) where e would be MyException but now if i see i can only have java.lang.Exception's methods not getValue()
You need to catch MyException specifically, not generic class Exception.

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.