Recent

4.Custom exceptions

Custom Exceptions – Exception Handling


A user defined exception or an exception which is made by the users to make the code print specific message when any exception occurs is known as custom exception.
We make custom exceptions due to the following reasons:
·         It makes our code easy to debug.
·         With custom exceptions we can print more specific message.
·         If we want an exception type that isn’t represented by those in the Java platform.
·         If our code throw more than one related exception.

QuestionCustom exception class is checked or not?
Answer: It depends upon the parent. If parent class which we are using to create a custom exception is checked then our custom exception will be checked else unchecked.

Example: Creating our own custom exception


import java.io.*;

//step 1: inherited the Exception class
//AgeException will be treated as the Exception name
class AgeException extends Exception
{

//Constructor is used to set a particular message for our exception
AgeException(String s)
{
super(s);
}}

//In class Demo we will use this custom exception
class Demo
{
int age;


void get(int age) throws AgeException
{

//If age<18 found, the exception will occur
if(age<18)
{
throw new AgeException("invalid age");
}

else
{
this.age = age;
}
}

public static void main(String[] s)
{

Demo d = new Demo();

try
{
//here exception occurs
d.get(10);
}

catch(AgeException e)
{
//printing the specific message here
System.out.println(e);
}
}
}
Output:

No comments:

Post a Comment

Bug-dbug Designed by Bugdbug - Developed by Belson Raja Copyright © 2016

Theme images by Bim. Powered by Blogger.
Published By Bugdbug India