5

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use exception.getStackTrace() if you want to do more with the stack trace.
3

Oracle's exception(s) tutorial

and

Java2s Examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.