Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an Exception source object

I was working on an assigment in Java, and I wondered if it's possible to know which object throwed an exception.

I know that if you make your custom exceptions, you can modify the constructor and have a reference to the object:

public class MyEx extends Throwable {
    private MyObject object;

    public MyEx(MyObject o){
        super();
    }

    public MyObject getSource(){
        return object;
    }
}

but I don't know if there exists another way of catching who throwed the exception. Do you know any other way?

like image 753
Roberto Luis Bisbé Avatar asked May 29 '11 09:05

Roberto Luis Bisbé


1 Answers

If you just want to see from which part of the code an exception is thrown, you have the simple stack trace. You get this by calling printStackTrace() on an exception instance.

This does not however give you the exact object instance that threw the exception. For this you have to implement a custom Exception like you indicated. Note that in some contexts there is no such thing as an instance, like e.g. an exception thrown from a static method.

like image 75
Arjan Tijms Avatar answered Sep 29 '22 13:09

Arjan Tijms