Powered by Blogger.

Java Coding: Creating and Throwing User Defined Exception in Java

Creating and Throwing User Defined Exception:-

By extending Exception class we can cerate our own Exception class.

general format for Exception Handling:-

    try
    {
        // Code blocks
    }
    catch(Exception1 e)
    {
        //Code to execute if exception of type 1 occured
    }
    ...
    catch(Exceptionn e)
    {
        //Code to execute if exception of type n occured
    }
    catch
    {
        //Code to execute if exception which not handled above occured
    }
    finally
    {
        //Code that must be executed
    }

If you provide empty catch and Exception catch then empty catch will never come in action as Exception catch will handle all the exceptions.

    private int Divide(int a, int b)
    {
        return (a / b); //it will create exception.
    }
    public void checkException()
    {
        try
        {
        int a = Divide(5, 0);
        //other exception causing statements.
        }
        catch (DivideByZeroException UE)
        {
        MessageBox.Show(UE.Message);
        }
        catch (Exception UE)
        {
        MessageBox.Show(UE.Message);
        }
        catch
        {
        //This will never execute.
        MessageBox.Show("Exception Occured.");
        }
        finally
        {
        MessageBox.Show("Finally");
        }
    }


In the above example we have defined empty catch and Exception catch as well but empty catch will never get attention. Also note that whenever an exception occurs it traverses back the call trace until it finds a try block after which the application terminates if none try block is occured. After getting exception created in statement reading “return(a/b)” it traverses to stack trace and reaches check Exception method where it get handles as there is a try block. If try catch block would be missing from there then application will terminate as it is the default implementation in Button Click. Please also note that there must be at least one catch statement for every try block.

Program:-

 public class MyException extends Exception{
   public MyException(String massage){
      super(massage);
   }

 public static void main(String[]args){
    try{
       throw new MyException(”User defined exception”);
    }catch(MyException e){
       System.out.println(e);
    }
   }
 }

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.

While defining an user defined exception, we need to take care of the following aspects:

1.  The user defined exception class should extend from Exception class.

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

Let us see a simple example to learn how to define and make use of user defined exceptions.


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 Custom Exception Test class, the age is expected to be a positive number. It would throw the user defined exception Negative Age Exception if the age is assigned a negative number.

At run time, we get the following exception since the age is a negative number. Exception in thread "main" Age cannot be negative -10
at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)

1 comment:

  1. I really enjoy the blog.Much thanks again. Really Great.
    Very informative article post. Really looking forward to read more. Will read on…


    oracle online training
    sap fico online training
    dotnet online training
    qa-qtp-software-testing-training-tutorial

    ReplyDelete