Skip to main content

User Defined Exception Handling

Introduction:

To develop the project, we must create our own Exception class, as Sun microsystem has not given any exception class some requirements which are not in common.
So, what is User defined exception is?
Exception class defined by Developer is called as User Defined Exception or Custom exception

Steps to create User Defined Exception:

  1. Write a class that extends java.lang.Exception.
  2. In User defined class, define minimum 2 constructors.
    1. No-argument constructor
    2. String parameter with logic “super(message)” to create exception object with message. 
  3. No need to define any method, why because exception class is not meant for developing business logic , instead it is used for terminating method logic execution by throwing it’s object.
------------------------------------------------------------------------------------------------------------
package com.app.exceptions;

/**
 *
 * @author Shashank Mungantiwar
 *
 */

public class NegativeNumberException extends Exception {
       private static final long serialVersionUID = 1L;
       public NegativeNumberException() {
              super();
       }
       public NegativeNumberException(String message) {
              super(message);
       }
}
----------------------------------------------------------------------------------------------------------

Why should we write super(message) statement in String parameter constructor, what is the internal problem?

  1. To pass the given message to Throwable class. To prepare it’s Exception object with given message.
  2. If you don’t write super(message), message is not handover to Throwable class and given message is not printed.

Why should we write User defined Exception or Custom Exception class subclassing from Exception class?

  1. We are writing custom exception to represent a condition failure logical mistake.
  2. So, when this exception is throw it must be report. Hence it should be subclass of Exception to be validated by compiler.
  3. We should derive or extend it from RuntimeException class only if we don’t want it validated by compiler or if we are writing it for representing operator failure.
  4.  We should extend it from Error class when we want to represent logical mistake occurred in JVM logic.
  5. We should extend it from Throwable to create separate category. It is not at all recommended.
  6. So, according to above point I explained, User defined class should be subclass of Exception class.
Now we will implement our custom exception-
----------------------------------------------------------------------------------------------------------
package com.app.bussinesslogic;

/**
 *
 * @author Shashank Mungantiwar
 *
 */

import com.app.exceptions.NegativeNumberException;

public class Addition {
       public static int add(int a, int b) throws NegativeNumberException {
              if (a < 0) {
                     throw new NegativeNumberException("Input first number=" + a + " should be non-negative");
              }
              if (b < 0) {
                     throw new NegativeNumberException("Input Second number=" + b + " should be non-negative");
              }
              return a + b;
       }
}
----------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------
package com.app.user;

/**
 *
 * @author Shashank Mungantiwar
 *
 */

import java.util.Scanner;
import com.app.bussinesslogic.Addition;
import com.app.exceptions.NegativeNumberException;

public class Calculator {
       public static void main(String[] args) throws NegativeNumberException{
                     @SuppressWarnings("resource")
                     Scanner scanner = new Scanner(System.in);
                     System.out.println("Enter First Number:");
                     int firstnumber = scanner.nextInt();
                     System.out.println("Enter Second Number:");
                     int secondnumber = scanner.nextInt();
                     int result = Addition.add(firstnumber, secondnumber);
                     System.out.println("Result=" + result);         
       }
}
----------------------------------------------------------------------------------------------------------
I will not write the output of above project , when input is given as negative number, you write  the code and execute it.

As per output , the Java exception message is not understandable by the User.
So, it’s  developer’s responsibility to convert java exception object message to end user understandable message relevant to current logical mistake.

How is it possible?

Yes. You guess it correct using try-catch block 
  1.  try establish a block to write exception causing statements and it’s related statements also we can write normal statements. 
  2. catch block is parameterised block used for catching the exceptions raised in it’s corresponding try block, and to define the logic to take necessary actions against that caught exception.
  3. Necessary actions include -
    1. Printing user understandable message relevant this exception.
    2. To stop abnormal terminations.
    3. To execute some other useful logic. 
  4. Rewrite Calculator program to print user understandable message, instead of java exception message.
  5. In above we got 2 exceptions-
    1. InputMisMatchException thrown by nextInt()  from Scanner class, if given input is not int type.
    2. NegativeNumberException thrown by add() method if given input is negative.  
  6. So, we must write 2 catch blocks to catch 2 exceptions separately to print user understandable message specific to exception as shown in below code snippet:
----------------------------------------------------------------------------------------------------------
package com.app.user;

/**
 *
 * @author Shashank Mungantiwar
 *
 */

import java.util.InputMismatchException;
import java.util.Scanner;
import com.app.bussinesslogic.Addition;
import com.app.exceptions.NegativeNumberException;

public class Calculator {
       public static void main(String[] args) {
              try {
                     @SuppressWarnings("resource")
                     Scanner scanner = new Scanner(System.in);
                     System.out.println("Enter First Number:");
                     int firstnumber = scanner.nextInt();
                     System.out.println("Enter Second Number:");
                     int secondnumber = scanner.nextInt();
                     int result = Addition.add(firstnumber, secondnumber);
                     System.out.println("Result=" + result);
              } catch (InputMismatchException inputMismatchException) {
                     System.out.println("Enter only Integer value...!!!");
              } catch (NegativeNumberException negativeNumberException) {
                     System.out.println("Please " + negativeNumberException.getMessage());
              }
       }
}

----------------------------------------------------------------------------------------------------------

Thank You ...!!!

Comments

Popular posts from this blog

Exception Propagation and throw-throws keyword

Exception Propagation: Sending exception from one method to another method is called exception propagation Here propagation is nothing but sending. So guys what is the situation when we are going to implement this propagation concept? Answer to this question is when we throw an exception, if it is not caught in that method it is propagated to another method and interesting thing is that we don’t need to do anything in this process we just need to throw an exception that’s it. Rule: If the propagated exception is checked exception then not only current method developer but also method’s caller method developer should caught or report that checked exception else it leads to same compiler exception….CE: Unreported Exception So according to that basic rule is “If checked exception is raised the method either directly by using throw keyword or indirectly by a method call it must be caught or reported. void m1() throws ClassNotFoundException{ ...

Restful API for Beginners

Introduction: Everyone is saying Rest API. Sometimes people say  only API to rest apis.RESTful API is for accessing blah blah service or to do blah blah functionality. In corporate world, fresher get confused when seniors give them task to create new api to call blah blah service or to do blah blah functionality. So what is this REST API? REST (REpresentational State Transfer) is an architectural style, and an approach to communications.Using this REST whatever functionality we create known as REST API. We can implement  rest-api using various providers but usually people use Jersey and Spring . As per my choice personally I would like to use jersey which keep code neat and clean. Rest follows client-server architecture with Front Controller Design Pattern. It completely depends on http protocol .REST implementation is very easy and run in  less memory compared to SOAP. Rest Support following parameter techniques to pass input for our web service...

Basic Exception Handling

What is Exception: Excetion is a runtime error caused due to logical mistake occured in the program beacause of wrong input given by the User. According  to Java language, value, message or excpetion everything is an object. In function programming, we return value. Throwing exception is like returning value and If we see according to User,methods are just services nothing else. What is our(developer's) responsibility: We must convert Java Exception message into End User Understandable.Here, Conversion I mean,catching Exception object and get information using getters provided such as getMessage() and modify this message with End user understandable format. Sun Microsystem(now Oracle) defined several classes to represent and handle logical mistakes. All these classes are defined in java.lang package with a super class Throwable. All Exception handling classes categorized into two sub-categories: Error Exception Exception classes a...