Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw custom Exceptions in Java/Android

I'm developing a custom Exception class, in which I have the following constructors:

public class UserException extends Exception
{
    string message;
    public UserException() {
        super();
    }

    public UserException(String message, Throwable cause)
    {
        super(message, cause);

        this.cause = cause;
        this.message = message;
    }
}

And I create a new custom exception like this:

private Camera.PreviewCallback SetPreviewCallBack() throws UserException {
    .......
    // Something went wrong
    throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
 }

But when I insert my throw new UserException(...) it tells me to surround it with try/catch!! That's not the idea, isn't it? I want to throw custom exceptions when I need them to be thrown, without surronding my new Exceptions with more try/catch clauses.

So, what I'm doing wrong? What I'm misunderstanding?

like image 371
Sonhja Avatar asked Feb 24 '15 10:02

Sonhja


1 Answers

In addition to Eran's answer, you could also make your custom Exception extend RuntimeException, which does not need to be caught.

like image 116
DennisW Avatar answered Sep 18 '22 05:09

DennisW