Can You write your own exeptions in Java ?

 
 

Yes. You have to extend Exception class. You’re not stuck using the existing Java exceptions. The JDK exception hierarchy can’t foresee all the errors you might want to report, so you can create your own to denote a special problem that your library might encounter. To create your own exception class, you must inherit from an existing exception class, preferably one that is close in meaning to your new exception (although this is often not possible). The most trivial way to create a new type of exception is just to let the compiler create the default constructor for you, so it requires almost no code at all:

class SimpleException extends Exception {}public class SimpleExceptionDemo {  public void f() throws SimpleException {    System.out.println("Throw SimpleException from f()");    throw new SimpleException();  }  public static void main(String[] args) {    SimpleExceptionDemo sed = new SimpleExceptionDemo();    try {      sed.f();    } catch(SimpleException e) {      System.err.println("Caught it!");    }  }}