Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

Custom Exception in Java

Sometimes it is required to develop meaningful exceptions or Custom Exception in java as per business requirement based on application, So we can create our own exceptions or custom exception by extending 'Exception' or RuntimeException class.

How to create Exceptions

To create own Exception we have to make our class Throwable type and to make our class throwable, we have to extends Throwable class or it's child class Exception or RuntimeException. Lets take an example

  Example 1:

  Example 2:
public class AgeNotValidException extends Exception {
	
	AgeNotValidException()
	{
	  super();
	}
	AgeNotValidException(String s)
	{
          super(s);
	}
}
public class MyCustomException {

  public void welcometoVote(int age) {
  	
  	if(age<18) {
  	  throw new AgeNotValidException();
  	}
  }
  public static void main(String args[]) {
  
  	 MyCustomException m=new MyCustomException();
  	 int age=15;
  	 try {
  	    m.welcometoVote(age);
  	  }catch(AgeNotValidException a) {
  	  	 a.printStackTrace();
  	  }
  }
}

Output

com.fruit.AgeNotValid
	at com.fruit.ExceptionTest.welcome(ExceptionTest.java:24)
	at com.fruit.ExceptionTest.main(ExceptionTest.java:31)