Creating our own Exceptions

Custom Exceptions

Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions. in the following example we have created an Except class which extends the Exception Class and method toString is overrided to return message to the calling try/catch block.

class Except extends Exception { // custom exception class extends main
									// Exception class
	public String toString() { // this will return a string back to the calling
								// block
		return "Custom Exception";
	}
}

public class OwnException {
	public static void main(String[] args) {
		int a = 100;
		try {
			if (a == 100) {
				throw new Except(); // throwing custom exception of Except
			}
		} catch (Exception e) {
			System.out.println(e); // print the toString Custome message
		}
	}
}