0

Possible Duplicate:
Is there a way to throw an exception without adding the throws declaration?

I wonder if there is a way to encapsulate Exception and rethrow it in another Exception when method is already defined and don't have throws clause.

An example (with JMS onMessage method) :

 public void onMessage(Message message) {

    if(message instanceof ObjectMessage){

        ObjectMessage objectMessage = (ObjectMessage)message;

        try {
            Object object = objectMessage.getObject();
        } catch (JMSException e) {
            throw new CustomException("blah blah", e); // ERROR HERE : Unhandled exception type CustomException
        }

     }

 }

So, how can I encapsulate and dispatch CustomException in my code please ? Is there a way ? Thanks

Community
  • 1
  • 1
Olivier J.
  • 3,115
  • 11
  • 48
  • 71

3 Answers3

4

You need to use a subclass of RuntimeException.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
3

If a method does not declare any exceptions, the only way is to throw an exception which subclasses of RuntimeException.

In your case CustomException should extend RuntimeException.

A bit of theory from Oracle on Exceptions.

Tom
  • 26,212
  • 21
  • 100
  • 111
1

This would have worked if CustomException was an unchecked exception (run time exception). You can read about checked vs unchecked exceptions here - Java: checked vs unchecked exception explanation

Community
  • 1
  • 1
Manish Mulani
  • 7,125
  • 9
  • 43
  • 45