Search code examples
javaexceptioncustom-exceptions

am developing API in java so i need to handle exceptions my customException class extends which class either Exception or Runtime Exception


my class extends which class please give me suggestion

public class MyException extends Exception {

    public MyException (Exception ex) {
        super(ex);
    }

    public MyException (String message) {
        super(message);
    }

    public MyException (Exception ex,String moduleKey) {
        super(ex, moduleKey);
    }

     public MyException (Exception ex, String moduleKey, String message) {
        super(ex, moduleKey, message);
    }

!-- end snippet -->


Solution

  • It all depends on whether you want to force API users to try/catch (or declare throws) every time your exception might be raised, or you want them to crash the application just like NullPointerException does.

    The first kind should be used whenever the exception is to be expected - like IOExceptions for instance. RuntimeExceptions usually suggest that something weird happend during (as the name suggests) runtime - a weird language behaviour, unexpected thread clash and so on. Usually you want to use the regular Exception though.