• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

User defined exception in java

June 6, 2012 By j2eereference Leave a Comment

User defined exception in java

An exception is a problem that arises during the execution of a program.  An exception can occur for many different reasons, including the following:

A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVM has run out of memory.

Some of these exceptions are caused by end user error, others by programmer error, and others by physical resources that have failed in some manner.Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter

In Java,Exceptions have been Categorized in two ways:

1. Java’s Built-In Exceptions

2. Custom Exceptions also called as User-Defined Exception

All Checked and Unchecked Exceptions are Java’s Built-In Exceptions.

You can create own customized exception as per requirements of the application. We know that for each application there are specific constraints. For Example, In case of Air Flight Booking, a passenger must specify the source ,destination place and age. Passenger must brings a ticket who is above the age of   3 years. Thus,Error-handling become necessary while developing a constraint application The Exception class and its subclass in java is not able to meet up the required constraint in application. For this, you create your own customized Exception to over address these constraints and ensure the integrity in the application

Developer can able to create their Own Exception Class by :

1.Extending the Exception class.

2.And the toString() method should be overridden in the user defined exception class in order to  display meaningful information about the exception.

3.If want to write a checked exception that is automatically enforced by the Handle or Declare Rule,  you need to extend the Exception class.

4.If want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{

}

EXAMPLE:

Lets create an Exception class to handle  age given in negative value.

NegativeAgeException.java

1
2
3
4
5
6
7
8
9
10
11
12
public class NegativeAgeException extends Exception {
 
    private int age;
 
    public NegativeAgeException(int age){
        this.age = age;
    }
 
    public String toString(){
        return "Age cannot be negative" + " " +age ;
    }
}

CustomExceptionTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class CustomExceptionTest {
    public static void main(String[] args) throws Exception{
        int age = getAge();
        if (age < 0){
            throw new NegativeAgeException(age);
        }else{
            System.out.println("Age entered is " + age);
        }
    } 
    static int getAge(){
        return -10;
    }
}

In the CustomExceptionTest class, the age is expected to be a positive number.

It would throw the user defined exception NegativeAgeException if the age is assigned a negative number.

 

At runtime, we get the following exception since the age is a negative number:

Exception in thread “main” Age cannot be negative -10

at com.j2eerference.corejava.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)

Related Posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.