OOPM JAVA - Create your own exception

 Experiment No. 13

Aim: Write a program to create your own exception. The exception will be thrown if number is odd.

Objective: To make aware of runtime error handling using Exception class and use for real time situations. 

Outcome: Students created own exception by inheriting the Exception class and successfully  implemented it.

Theory:

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

What is exception?

Dictionary Meaning: Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. 

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error


1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


hierarchy of exception handling


Customized Exception Handling : Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.


Algorithm:

1. Create a class OwnException which is subclass of builtin class Exception with data 

member int no and member function

    1 OwnException(int no I)

    2 toString( )

 2. In procedure OwnException(int no I)

    no=nol

 3. In procedure toString ( )

    retutn "Exception odd number"

 4. Create a class ExceptionDemo with main function and a static function

    void evenodd(int n) throws OwnException

5. In procedure evenodd(int n)

    5.1 if(n%2==0)

    Print number is even

    5.2 else

    Throw exception

6 In try block

    6.1 call evenodd(20)

    6.2 call evenodd(50)

7 In catch block

    Print caught exception

8. Stop


Code : 

import java.util.Scanner;

    class OddNumberException extends Exception 

    {

        OddNumberException()

        {

            super("Odd number exception");

        }

        OddNumberException(String msg)

        {

            super(msg);

        }

    }

 

    class UserdefinedException

    {

        public static void main(String[] args)

        {

            int num;

            Scanner Sc = new Scanner(System.in);

            System.out.print("Enter any number : ");

            num = Integer.parseInt(Sc.nextLine());

            try

            {

                if(num%2 != 0)

                    throw(new OddNumberException());   

                else

                    System.out.print("\n" + num + " is an even number");

            }

            catch(OddNumberException Ex)

            {

                System.out.print("\nError : " + Ex.getMessage());

            }

        }

    }

    

Output : 

Creating Your own Exception

Observations and learning: 
With the help of this experiment we learnt to create our own exception in java. In this experiment we created exception for odd number.
 
Conclusion: 
We created our own exception for detecting odd number. 
 
Question of Curiosity 
1. What is Exception in Java?
Ans : In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
 
2. What are the Exception Handling Keywords in Java?
Ans : Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
 
3. Explain Java Exception Hierarchy?
Ans : Java exception classes are organised into a fundamental hierarchy at the very top level. There is a basic exception class called Exception as you might expect. But in fact, the base of the hierarchy starts not with Exception but with a class called Throwable, which is then subclassed into Exception and Error.
 
4. What are important methods of Java Exception Class?
Ans : 
  • public Throwable getCause() – Returns the cause of this throwable or null if the cause is nonexistent or unknown. 
  • public String getLocalizedMessage() – Creates a localized description of this throwable. Subclasses may override this method in order to produce a locale-specific message. For subclasses that do not override this method, the default implementation returns the same result as getMessage().
  • public String getMessage() – Returns the detail message string of this throwable.
  • public void printStackTrace() – Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace().
  • public String toString() – Returns a short description of this throwable. The result is the concatenation of:
                        – the name of the class of this object
                        – “: ” (a colon and a space)
                        – the result of invoking this object’s getLocalizedMessage() method
If getLocalizedMessage returns null, then just the class name is returned.
 
5. What is difference between throw and throws keyword in Java?
Ans : Throws clause is used to declare an exception, which means it works similar to the try-catch block. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.


Comments