Writing your own custom exception in Java. Writing your own exception in java is very simple. All you need to do is just extend "Exception" class.
public class MyException extends Exception
public MyException(String message)
Analysis of the above code
"MyException" is our exception class name. You can give any name of your choice.
Important thing to be noted is our class extends "Exception" class. This is all we need to do make a custome defined exception
"Now we define a constructor of my class. This constructer takes a "String" argument. We call super class' constructor(super class here is "Exception class") and pass this string to it. Not java creates a new Exception with the message as in the string passed.
2. Using the custome defined exception
Let's see how we can use the exception "MyException" that we created now. We are going to write a class which will display numbers 1 to 6 and then throw our "MyException"
public class ExceptionDemo
public static void main(String args) throws Exception
ExceptionDemo exceptionDemo = new ExceptionDemo();
public void displayNumbers() throws MyException
throw new MyException("My Exception Occurred");
Core Java Interview Questions
Object Oriented Programming(OOP) Questions and Answers
Collections Interview Questions
Java Exceptions Interview Questions
Java Threads Interview Questions
Collection framework in java interview questions
oops concepts with example in java
Java Serialization Interview Questions
Top 20 Core Java Interview Questions with Answers
String Interview Question in java With Example
synchronization interview questions
Java Reflection Interview question
Java Executor Framework (JDK 1.5) Interview Questions
JDK 1.7 interview Questations and Answers
Java I/O interview question with example