Saturday 25 December 2021

Creating user defined exceptions in java

There may be times when we would like to throw own exceptions. We can do this by using the keyword throw as follows:

throw new throwable's subclass;

Example:

1. throw new IOException(" my IOException");

2. throw new NumberFormatException(" invalid number exception");

Sometimes, the built-in exceptions in java are not table to describe a certain situations. In such cases, like predefined exceptions, the user ( program written by user) can also create his own exceptions which are called " user defined exceptions". The following are the steps to create a user defined exception

1. The user should create an exception class as a subclass to Exception class.

          Example: class MyException extends Exception

2. If you don't need to store the exception details, create a default constructor for your user defined class.

3. The user can create a parameterized constructor with a string as a parameter. He can use this to store exception details. He can call super class (Exception) constructor from this and send the string there.

4. When the user wants to raise his own exception, he should create an object to his exception class and throw it using throw keyword.

The following program demonstrates how to create a user defined exceptions in java

import java.lang.Exception;
class MyException extends Exception  
{ 
	 MyException( String msg)
	{
		 super(msg);
	}
} 

class userDefinedException
{
	public static void main(String[] args) 
	{
		int x=5,y=1000;
		try
		{
			float z=(float)x/(float)y;
			if(z<=0.01)
			{
				throw new MyException(" number is too small");
			}
		}
		catch (MyException ex)
		{
			System.out.println("Caught my exception");
			System.out.println(ex.getMessage());
		}
		finally
		{
			System.out.println("You are in the finally block");
		}
	}
}


Output

 
D:\java examples>javac userDefinedException.java
D:\java examples>java userDefinedException
Caught my exception
 number is too small
You are in the finally block


0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top