This is a simple custom exception in java. That is, we can create an exception by extending the exception class.

The “throw new MyExcep” will throw an exception and the error message we specified will be displayed

import java.lang.Exception;
@SuppressWarnings("serial")
class MyExcep extends Exception
{
	MyExcep(String Errormsg)
	{
		super(Errormsg);	// call Exception class error message
	}
}
public class Example
{
	public static void main(String[] args)
	{
		int x = 5 , y = 1000;
		try
		{
			float z = (float) x / (float) y;
			if(z < .01)
			{
				throw new MyExcep("Number is too small");
			}
		}
		catch(MyExcep e)
		{
			System.out.println("Caught My Exception");
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("I am Always Here");
		}
	}
}

The output will be like this

Caught My Exception
Number is too small
I am Always Here

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.