Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an Exception 'OrekitException' that I want to wrap into my own Exception class.
How can I go about this?
e.g. In one of my methods:
private void configureOrekit() throws OrekitException{
try {
method logic...
} catch (OrekitException oe) {
System.out.println(OrekitException oe);
log.error(oe.getMessage());
}
My own Exception class:
public class MyException extends Exception {
public MyException ( String message )
{
super( message );
}
}
How can I incorporate OrekitException in MyException so whenever it is thrown, it's out of the MyException class?
Provide a constructor that also accepts the exception to wrap :
public class MyException extends Exception {
public MyException (String message, OrekitException exception){
super(message, exception);
}
}
or to wrap any exception use a broader type for the parameter :
public MyException (String message, Exception exception){
super(message, exception);
}
You could use it as :
private void configureOrekit() throws MyException{
try {
method logic...
} catch (OrekitException oe) {
throw new MyException("message useful...", oe);
}
Note that System.out.println() is not a way to trace an exception and that logging an exception and then wrap it in another exception that you throw is not good as you could still log it at any layer, it would make things not clear at all to find some duplicate error logs in log files...
In a general way, either log or throw/propagate the exception : not both.
Exceptions allow you to specify a cause. You can take a cause in your constructor, and pass it to Exception's constructor:
public class MyException extends Exception {
public MyException (String message, Exception cause){
super(message, cause);
}
}
And your method can then throw MyException:
private void configureOrekit() throws MyException{
try {
method logic...
} catch (OrekitException oe) {
System.out.println(OrekitException oe);
log.error(oe.getMessage());
throw new MyException("", oe);
}
}
This allows the stack trace from your MyException objects to have caused by... show details/trace of the original OrekitException
Related
I have a generic function which does something and, in case of failure, it should throw a specific exception.
To simplify you can imagine it as such:
public static <E extends Exception> void doSomething(Class<E> exceptionClass) throws E {
try {
//Do stuff
} catch (Exception e) {
String message = "...";
//-> here I want to throw a new exception of type E with the message I built above and the caught exception as cause
}
}
In order to do that, what I can think about is to build a new E by reflection and throw an unchecked exception if any of the exceptions that can be thrown during reflection is actually thrown:
public static <E extends Exception> buildException(Class<E> exceptionClass, String msg, Throwable cause) {
try {
return exceptionClass.getDeclaredConstructor(String.class, Throwable.class).newInstance(msg, cause);
} catch (NoSuchMethodException ... e) {
//Catch everything that can be thrown
throw new RuntimeException(e);
}
}
... and then call it simply throw buildException(exceptionClass, message, e) inside the main function.
However I don't like too much this solution because I need to get the class in parameter from the caller (while they are already inferring me the type via E) and I may as well have to throw a Runtime exception if my reflection operation fails (all E extends Exception so the constructor I look for should always be there, but we never know if the caller doesn't customize the exception too much...)
Although the drawbacks, I can't get anything better into my mind.
Does anyone have some better design ideas for this?
Note: about the need. I have several classes which perform the same operation (the "do stuff") but that need to throw a specific exception (class 1 throws exception 1, class 2 throws exception 2 etc.) which wraps any possible exception thrown while performing the "do stuff" operation. Of course I may move the catch on caller side but that would make a lot of code duplication for the exact same operation.
Instead of passing the class and let the called method handle the exception creation you could let the calling method handle it instead. This is possible by accepting a function:
public static <E extends Exception> void doSomething(Function<String, E> exceptionFunction) throws E {
try {
//Do stuff
} catch (Exception e) {
String message = "...";
throw exceptionFunction.apply(message);
}
}
This function would expect a String, your message, and will then return an instance of the exception to be thrown. As you can see, you can trigger the function by using exceptionFunction.apply(message).
You can also use e to add the "cause" stacktrace:
public static <E extends Exception> void doSomething(Function<String, E> exceptionFunction) throws E {
try {
//Do stuff
} catch (Exception e) {
String message = "...";
var exception = exceptionFunction.apply(message);
exception.initCause(e);
throw exception;
}
}
The call of the doSomething method would then look like this:
doSomething((s) -> new MyException());
or if you prefer method references, like this:
doSomething(MyException::new);
(mind that MyException would need a constructor with a String parameter)
This question already has answers here:
Rethrow exception in java
(7 answers)
Closed 7 years ago.
public void init() throws SocketException
{
try
{
socket = new DatagramSocket(4446);
}
catch (SocketException se)
{
throw se;
}
}
and
public void init() throws SocketException
{
socket = new DatagramSocket(4446);
}
Are the two chunks of code essentially the same or are they different in behavior to a caller who calls this init method?
Will the exception received by caller of this method have same information and exactly same stack trace?
The stack trace you will get will be exactly the same as can easily be proved by a simple experiment. In terms of code execution, there will be extra handling of the exception in the first example, but no significant difference in behaviour
If the deeper exception needs to be caught, it would be more usual to wrap the exception or exceptions in a new exception with the original exception used as an argument, in which case you will get two stack traces - one from init() and one from the original exception.
throw new RuntimeException(se);
from the callers point of view they are same, caller must either catch SocketException or add throws SocketException.
The only issue is that in some case calling method may not be allowed to use throws in declaration as SocketException is a checked exception.
Will the exception received by caller of this method have same
information and exactly same stack trace ?
yes, because your not throwing a new exception from init().
There is not differences at all, but sometimes, if a process fail, you want to add some logic before rethrowing the exception (like closing a connection).
public void init() throws SocketException {
try {
socket = new DatagramSocket(4446);
} catch (SocketException se) {
// damn, it failed, lets do something before throwing.
throw se;
}
}
And as #Ramanlfc pointed out, sometime you implement an interface and cannot throw checked Exception.
#Override
public void init() {
try {
socket = new DatagramSocket(4446);
} catch (SocketException e) {
throw new RuntimeException("Failed to create DatagramSocket on port 4466", e);
}
}
Here we encapsulate the exception and we are adding another level in the stackstrace.
Can anyone please give me information about it. I cant really uderstand the type of this Exception.
Thank you
public class ValidationException extends Exception{
public ValidationException(){
super("There was a problem when validating data");
}
public ValidationException(String message){
super(message);
}
public ValidationException(String message, Throwable throwable){
super(message, throwable);
}
public ValidationException(Throwable throwable){
super(throwable);
}
}
It is a "runtime exception" in the (fatuous) sense that it is an exception that occurs at runtime. But that is true for all Java exceptions ... apart from bugs in the compiler, etcetera.
It is not a subclass of RuntimeException. You have declared it as a subclass of Exception and Exception is not a subclass of RuntimeException. (In fact, the reverse is true: RuntimeException is a subclass of Exception!)
It is a checked exception because it is not a subclass of RuntimeException (or Error).
Since it is a checked exception, the Java rules about checked exceptions apply. For example, any method that throws or propagates1 your exception must declare that it throws this exception, or an exception that is a superclass of this exception.
1 - Technically, the JLS describes this as an abnormal termination of the method body with this exception as the abnormal termination reason.
The main difference between Exception, and RuntimeException is that we need to wrap a Exception in a try/catch block. A RuntimeException does not need to be caught, but it is just as lethal as an Exception.
public class Main{
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler(){
#Override
public void uncaughtException(Thread t, Throwable e){
System.out.println("Uncaught Exception " + e);
}
});
try{
throwException();
}catch(Exception e){
System.out.println("Caught Exception " + e);
}
try{
throwRuntimeException();
}catch(Exception e){
System.out.println("Caught RuntimeException " + e);
}
//unchecked, no need to wrap int try/catch
throwRuntimeException();
}
public static void throwException() throws Exception {
throw new Exception();
}
public static void throwRuntimeException() {
throw new RuntimeException();
}
}
Take this example above. The output is this:
Caught Exception java.lang.Exception
Caught RuntimeException java.lang.RuntimeException
Uncaught Exception java.lang.RuntimeException
As you can tell, the call to throwRuntimeException() gets thrown, and since there is no try/catch block it has no idea how to handle it. This crashes the thread and since there is an UncaughtExceptionHandler it gets called.
Then there is also Error which I won't go into since I don't know much about it besides that JVM throws it. OutOfMemoryError is an example.
I have a method, in which right now I am handling the exception using the try catch method.
I have a custom exception method to handle the error.
Now I have to change this exception handling to runtime exception.
Code:
public class AppException extends RuntimeException {
private static final long serialVersionUID = -8674749112864599715L;
public AppException() {
}
public AppException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public AppException(String message, Throwable cause) {
super(message, cause);
}
public AppException(String message) {
super(message);
}
public AppException(Throwable cause) {
super(cause);
}
}
Method which handled using try catch.
#Transactional(readOnly = false)
#Override
public String save(StagingDocument stagingData)
throws AppException {
String enrichObjectId = null;
try {
EnrichDocument document = getEnrichDocument(stagingData);
EnrichDocument enrichPayload = enrichStagingDocumentRepository
.save(document);
enrichObjectId = enrichPayload.getId().toString();
} catch (Exception e) {
logger.error("EXCEPTION IN SAVETOENRICHDOCUMENT METHOD: " + e);
throw new AppException (e.getMessage(), e.getCause());
}
return enrichObjectId;
}
Here in the above method is the implementation when AppException extends the Exception class.
Now I need to change the save method according to runtime exception handling.
Question:
How can I change this method,without using try catch method?
If try catch is not there how the exception is get handled?
RuntimeExceptions don't have to be declared in the method signature, and if you want to remove the try/catch blocks as well - you can do it:
#Transactional(readOnly = false)
#Override
public String save(StagingDocument stagingData) {
String enrichObjectId = null;
EnrichDocument document = getEnrichDocument(stagingData);
EnrichDocument enrichPayload = enrichStagingDocumentRepository
.save(document);
enrichObjectId = enrichPayload.getId().toString();
return enrichObjectId;
}
When there's no try/catch - the exception doesn't get "handled" it is rather getting cascaded until either a higher level handles it or until the highest level exists the program (with the RuntimeException).
If you don't use a try-catch block, the original Exception would not be caught. If it is a RuntimeException, you will get no compilation errors as RuntimeExeption does not need to be caught. If that Exception occurs, it will simply be thrown from the save() method (it will be delegated).
If the original Exception is not a RuntimeException and you don't want to use a try-catch block, you may declare the save() method to throw that Exception but in this case it will obviously be not an instance of AppException but the original exception itself.
Btw, if you create an AppException, its cause should be e and not e.getCause(). If you pass e.getCause() as the cause of your AppException, then e itself will be lost. You might also want to add a custom error message and not use the original exception's message.
Summary: if you want your save() method to throw an instance of AppException if an Exception is encountered inside, you can't do that without a try-catch block, you have to catch it (the Exception encountered inside) and wrap it in a new AppException like you did.
Runtime exceptions need not be caught. If you are using AppException as a checked exception, still you need not put try/catch since you have already handled it using throws in the method signature. The method which is calling save() will have to handle the AppException.
This question already has an answer here:
Junit Test Case for exception [closed]
(1 answer)
Closed 7 years ago.
I'm using JUnit and not quite sure how to test custom exception class. I have created,
public class CustomException extends Exception {
//#param message is the exception message
public CustomException(final String message) {
super(message);
}
//#param message is the exception message
//#param cause is the cause of the original exception
public CustomException(final String message, final Throwable cause) {
super(message, cause);
}
}
main class would have many try catch such as:
catch (ParseException e) {
throw new CustomException("Date format incorerect", e);
and I'm not sure how to write the test class for it.
This page should tell you everything you need to know. For the simplest case, which seems to be your case, just do this:
#Test(expected= CustomException.class)
public void myTest() {
MyObject obj = new MyObject();
obj.doSomethingThatMightThrowCustomException();
}
I hope this can help you.
public class YourTestClass
{
#Test
public void yourTestMethodName() throws CustomeException {
//your logic goes here.
if (condition) {
throw new CustomeException(<Message to display while throwing an error>);
}
}
}
Also you can try the following site http://junit.sourceforge.net/javadoc/org/junit/Test.html