Sunday, January 24, 2016

How to Create User defined Exception In Java

In This Post We Will discuss custom exceptions or  User defined Exception in java, In the earlier post we had already discussed Exception Handling in java. You just go through that link to aware of exception in java.While developing  in your programming  projects you will be required to define Custom Exception or User defined Exception.

User defined Exception means Exception class is created by user.Some of the Built in Exception classes are provided by the Exception and error classes may not be enough to trap errors occurring in the program.You can also see this link top exceptions in java frequently raising while developing programming project.So in some cases you need to create your own exceptions. User defined class should be subclass of Exception class.

Why we Use Custom Exception in Java: 

User defined Exceptions is use to show custom messages to the end users. And also used to hide null pointer exception,arithmetic Exception. So custom exceptions used in our programming project very commonly.


Procedure to create User defined Exception in java:

To create user defined exception we need to write subclass simply extending the java Exception class and you can override toString()function to display your customize message on catch.
  
In the Exception class provides methods to show error message to the end users.They are




















While you want to develop user defined exception in your programming project no need to override any of the above methods which are available in the Exception class in the sub class. Based on your project requirement you have to customize your message to show end users.

Example: Create Custom defined Exception

class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{
super(s);
}
}
class TooOldException extends RuntimeException
{
TooOldException(String s)
{
super(s);
}
}
class CustomExceptionDemo
{
public static void main(String arg[])
{
int age = Integer.parseInt(arg[0]);
if(age > 60)
{
throw new TooOldException("Younger age is already over");
}
else if(age <18)
{
throw new TooYoungException("Please wait same more time");
}
System.out.println("Thanks for register");
}
}

Output:




Note: You can Override toString() method to display custom message.
           You must extend the Exception class to create custom exceptions 







No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...