How to create your own Exception class

While developing applications in Java, you would often need to create your own Exceptions based on the need, along with built in Exception classes like ClassNotFoundException, NumberFormatException, ArithmeticException, ArrayIndexOutofBoundsException, etc… You can also create your own Exceptions, TestException

Below is an example to create an Exception class,

//Create our own Exception
class TestException extends Exception
{
	public String toString()
	{
		return "This is only Test Exception";
	}
}

public class MyOwnExceptionDemo {
	public static void main(String[] args) {
	try
	{
		throw new TestException();
	}
	catch(TestException te)
	{
		te.printStackTrace();

		//How to get class name from an object
		System.out.println("Exception class name:"+te.getClass().getName());
		System.out.println(te.toString());
	}
	}

}

You may also like to read:
what is printStackTrace() method
Output printStackTrace() to a String
Purpose of synchronized keyword