Monday, May 8, 2017

[Java][Example] Defining custom Exception


Steps to create custom Exception in Java :

  1. Create a class named with your custom exception name you want.
  2. Make your class extends  Exception class.
  3. Define a constructor named with your class name and call Exception(String message) method.

Example 

package javaapplication3;

public class DoorLock  {
    private boolean locked=true;
    private String user1=null, user2=null;
    public synchronized void lock(String userid)
            throws SameUserException, NotLockedException  {
        if (!locked) {
            throw new NotLockedException();
        }
        if (user1==null) {
            user1=userid;
            try {
                wait();
            } catch (Exception e) {

            }
        } else if (user1.equals(userid)) {
            user2=userid;
            notify();
            locked=false;
        } else {
            throw new SameUserException();
        }
    }

    public synchronized void unlock(String userid)
            throws LockedException, NotAllowedException {
        if (locked) {
            throw new LockedException();
        }
        if (user1.equals(userid) || user2.equals(userid)) {
            user1=user2=null;
            locked=true;
        } else {
            throw new NotAllowedException();
        }
    }
}

Sample 1 : SameUserException.java


package javaapplication3;

class SameUserException extends Exception {
    //Parameterless Constructor
    public SameUserException(){
        super("SameUserException is catched");
    }
    //Constructor that accepts custom message
    public SameUserException(String msg){
        super(msg);
    }   
}

Sample 2 : LockedException.java

package javaapplication3;

class LockedException extends Exception {
    public LockedException(){
        super("LockedException is catched");
    }       
}

Sample 3 : NotLockedException.java

package javaapplication3;

class NotLockedException extends Exception {
    public NotLockedException(){
        super("NotLockedException is catched");
    }   
}

Sample 4 : NotAllowedException.java

package javaapplication3;

class NotAllowedException extends Exception {
    public NotAllowedException(){
        super("NotAllowedException is catched");
    }      
}

Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
http://stackoverflow.com/questions/8423700/how-to-create-a-custom-exception-type-in-java

No comments :

Post a Comment