In this article we will see what are 'User defined exceptions in Java', and how to define and use user defined exceptions with example.

User defined exceptions can be created as a class extending 'Exception' as shown below:
class MyException extends Exception {

}
There is no need to writing anything inside the user defined exception classes, optionally these classes can have constructors and can override toString() as well.
class MyException extends Exception {
	public MyException() {
		super();
	}

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

	public String toString() {
		return "MyException";
	}
}
Above user defined exception can be thrown as shown below:
	void printSize(String string) throws MyException {
		if (string == null)
			throw new MyException();
		if (string.length()<10)
			throw new MyException("Length is less than 10");
	}
Using user defined exceptions, the programmer can define the behaviour of unexpceted inputs.

User defined Exceptions example

Here is complete example of how, User defined Exceptions can be defined and used in Java:
package com.tb.demo;

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

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

	public String toString() {
		return "MyException";
	}
}

public class Impl {

	void printSize(String string) throws MyException {
		if (string == null)
			throw new MyException();
		if (string.length() < 10)
			throw new MyException("Length is less than 10");
	}

	public static void main(String[] args) {
		Impl impl = new Impl();
		try {
			impl.printSize("String");
		} catch (MyException e) {
			System.out.println(e);
		}
	}

}
Output: Output will be somwthing like this:

MyException


In this article we have seen what are 'User defined exceptions in Java', and how to define and use user defined exceptions with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java