×

Java Programs

Java Practice

Use of all the user defined exception keywords in a single Java program

In this article, we will be using all the user-defined exception keywords in a single java program.
Submitted by Raunak Goswami, on October 08, 2018

As we know that Java provides an efficient mechanism for handling the exception but still user has the option to define its own exception in Java, using try-catch blocks or using throw keyword. List of various user-defined exception keywords provided in Java is as follows:

  1. Try
  2. Catch
  3. Throw
  4. Throws
  5. Finally

Let us write a simple java code which includes all these keywords

import java.io.IOException;
import java.util.Scanner;

public class Main
{
	static void ex(int a)
	{	
		try
		{
			int c =50/0;
		}
		catch(ArithmeticException e)
		{
			System.out.println("dividing a number by zero cannot be defined");
		}
		finally
		{
			System.out.println("this statement will always be executed");
		}

		if(a>=18)
			throw new ArithmeticException("The person is  eligible to vote");
		else
			System.out.println("the person is not eligible to vote");
	}

	public static void main(String [] args) throws Exception
	{ 
		Scanner sc = new Scanner(System.in);
		System.out.println("enter the age of a person to check for voting");
		int c =sc.nextInt();
		ex(c);
		System.out.println("This is written inside main function");
	}
}

Output

First run:
enter the age of a person to check for voting
12
dividing a number by zero cannot be defined
this statement will always be executed
the person is not eligible to vote
This is written inside main function

Second run:
enter the age of a person to check for voting
34
dividing a number by zero cannot be defined
this statement will always be executed
Exception in thread "main" java.lang.ArithmeticException: The person is  eligible to vote
        at Main.ex(Main.java:22)
        at Main.main(Main.java:32)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.