TransWikia.com

Caught and declared exception in Java?

Stack Overflow Asked by Hrvoje T on December 26, 2020

In Java, if I declare and caught an exception, can I handle the exception in a caller anyway? Or it needs not to be caught to handle it by caller?

class A {
  void first() throws Exception { 
    try {
      throw new Exception("my exception")
    } catch (Exception e) {
      log.message("Error in first()", e.getCouse)
      throw e
    }
  }
}

class B {
  Result second(A a) {
    try {
      a.first()
    } catch (Exception e) {
      log.message("Caught in B class", e.message)
      return new Result(result: null, error: e.message)
    }
  }

  second(A a)
}

One Answer

You can simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

catch (WhateverException e) {
    throw e;
}

You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:

try
{
   ...
}
catch (Exception e)
{
     throw new YourOwnException(e);
}

Correct answer by anurag saxena on December 26, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP