AnswerBun.com

Caught and declared exception in Java?

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)
}

Stack Overflow Asked by Hrvoje T on December 26, 2020

1 Answers

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!

Related Questions

Polygons from line segments

3  Asked on November 27, 2021

         

JSLint: Disallow state. in Redux connect functon

0  Asked on November 27, 2021 by hakunin

       

Copy content of SQL Server 2016 db

4  Asked on November 27, 2021 by mjpolak

     

How to disable autofix for specific rules in eslint using CLI?

2  Asked on November 27, 2021 by chevybow

 

Managing multiple sites on XAMPP

1  Asked on November 27, 2021 by moeez

         

How to find what library provides the import?

1  Asked on November 27, 2021 by daneel-yaitskov

     

Wait for forEach with a promise inside to finish

2  Asked on November 27, 2021 by inbahn

 

Solving modular linear congruences for large numbers

2  Asked on November 27, 2021 by oppressionslayer

         

Sort 3D eigenvector array using eigenvalues

1  Asked on November 27, 2021 by t-a

         

Interpolation of values from list

3  Asked on November 27, 2021

   

How can I delete a specific character from set of tuples?

2  Asked on November 27, 2021 by determindedelixir

         

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.