Exceptions in Java can be divided into two categories;Checked and Unchecked exceptions.

In general checked exceptions must be caught or re thrown while uchecked exceptions may occur during the execution of a program â??due to wrong method arguments etc-.

Creating custom checked exceptions

Checked exceptions extend the Exception class.In our example:


public class CustomCheckedException extends Exception{

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

Suppose now that we use CustomCheckedException in a method of a test class;


public class ExceptionTestClass {

	
	
	public void aMethod(int argument) throws CustomCheckedException{
		
		if(argument==1){
			throw new CustomCheckedException();
		}
	}
	
}

As you can she in the above snippet the method that uses CustomCheckedException must declare that is handling it and this is done in our case with throws.

Finally,if we use it in a main method:

public class ExceptionTest {
	
	public static void main(String args[]){
		ExceptionTestClass test=new ExceptionTestClass();
		
		try {
			test.aMethod(1);
		} catch (CustomCheckedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

Creating Custom Unchecked exceptions

In order to create an unchecked exception our exception class must extend RuntimeException.For example:


public class CustomUncheckedException extends RuntimeException{

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

The custom unchecked exception can be used as in the below example:


public class ExceptionTestClass {

	public void anotherMethod(int argument){
		if(argument==2){
			throw new CustomUncheckedException();
		}
	}
}

Note that in the above example there is no need to for the method that uses CustomUncheckedException to handle it either by catching or throwing the exception. Finally anotherMethod() can be called as in the following example:

public class Ggre {
	
	public static void main(String args[]){
		ExceptionTestClass test=new ExceptionTestClass();
	
		test.anotherMethod(2);
	}
}