custom exceptions in java


Exceptions:
Three types of exceptions in java
·      Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
·      Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
·      Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Custom exceptions Example:
package com.anjana.customexceptions;

public class MyException extends Exception{
 
  MyException(String message){
       
        super(message);
  }

}
package com.anjana.service;
import com.anjana.customexceptions.*;

public class TestException1 {
 
  public boolean testme(int a)throws MyException{
       
        if(a==0){
              throw new MyException("Throwing custom exception");
        }
        return true;
       
  }
 
  public static void main (String args[]){
        TestException1  te=new TestException1();
        try{
              Boolean bo=te.testme(0);//passing 0 to get exceptions
              System.out.println(bo+"bo");
        }
  catch(MyException me){
        me.printStackTrace();
}
       
  }

}

Output:
com.anjana.customexceptions.MyException: Throwing custom exception
  at com.anjana.service.TestException1.testme(TestException1.java:9)
  at com.anjana.service.TestException1.main(TestException1.java:18)

Comments

Popular posts from this blog

defining functions clojure

Integrating Struts2 with Spring Security using Custom Login Form