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:
- Checked Exception
- Unchecked Exception
- 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.
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 :
- 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:
– “: ” (a colon and a space)
Comments
Post a Comment