Saturday 25 December 2021

Throw and Throws keywords in Java

There could be situations where there is a possibility that a method might throw certain kinds of exceptions but there is no exception handling mechanism prevalent withing the method. In such a case, it is important that the method caller is initiated explicitly that certain types of exceptions could be excepted from the caller method, and the caller must get prepared with some catching mechanism to deal with it.

The throws keyword is used in such a situation. It is specified immediately after the method declaration statement and just before the opening brace. Check Here how throw works
 
The main difference between throw and throws is 
 
throws clause is sued when the programmer does not want to handle the exception and throw it out of a method. throws clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence throws and throw are contradictory.

Example

class ThrowsDemo 
{
	static void divide() throws ArithmeticException
	{
		int x=22,y=0,z;
		z=x/y;
	}
	public static void main(String args[])
	{
		try
		{
			divide();
		}
		catch (ArithmeticException ex)
		{
			System.out.println(" caught the exception " +ex);
		}
}
}


Output
D:\java examples>javac ThrowsDemo.java
D:\java examples>java ThrowsDemo
 caught the exception java.lang.ArithmeticException: / by zero

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