0

Can we create an custom exception for a class Level. For example I have a Class A, now when I create a given object or When I call a given method, I would like yo throw my custom exception.

1
  • I haven't understand the question, do you mean how to create our own exception? Commented May 14, 2016 at 11:21

2 Answers 2

2

This is the easiest way to create your own Exception:

public class LevelException extends Exception {
    public LevelException(String message) {
        super(message);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You have two kind of exceptions checked and unchecked exceptions.

  1. Unchecked exceptions are the sub classes of RuntimeException, those exceptions don't need to be added explicitly in your method/constructor description, calling code doesn't have to manage it explicitly with a try/catch block or by throwing it.
  2. Checked exceptions are the sub classes of Exception but not the sub classes of RuntimeException, those exceptions need to be added explicitly in your method/constructor description, calling code have to manage it explicitly with a try/catch block or by throwing it.

Depending of your need, you will chose one of the two possibilities, if you want to enforce calling code to manage it, use checked exceptions otherwise use unchecked exceptions.

Unchecked exceptions

How to create it:

public class MyException extends RuntimeException {
...
}

How to use it:

public void myMethod() {
    ...
    if (some condition) {
        throw new MyException();
    }
    ...
}

Checked exceptions

How to create it:

public class MyException extends Exception {
...
}

How to use it:

public void myMethod() throws MyException {
    ...
    if (some condition) {
        throw new MyException();
    }
    ...
}

You can find more details about exceptions here

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.