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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With