Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Exception Handling. No Comments on throw throws and finally
0
(0)

In this article we will look at the use of throw throws and finally keywords of exception handling in Java programs.

 

throw Keyword

 

The throw keyword can be used in Java programs to throw exception objects explicitly. The syntax of using throw is as follows:

 

throw ThrowableInstance;

 

The ThrowableInstance can be object of Throwable class or any of its sub classes. A reference to the Throwable instance can be obtained using the parameter in catch block or by using the new operator.


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


 

Let’s see a sample program that demonstrates the use of throw:

class ArrayException
{
	public static void main(String[] args)
	{
		try
		{
			throw new ArithmeticException("Testing throw");
		}
		catch(Exception e)
		{
			System.out.println(e);
			throw e;
		}
	}
}

 

At line 7 throw keyword is used to throw a n object of ArithmeticException with the message Testing throw. At line 12 we are re-throwing the exception to Java run-time system. Output of the above program is:

 

java.lang.ArithmeticException: Testing throw
Exception in thread “main” java.lang.ArithmeticException: Testing throw
at ArrayException.main(ArrayException.java:8)

 

throws Keyword

 

The throws keyword can be used in method definition to let the caller of a method know about the exceptions that the method might raise and which are not handled by that method. The general form of throws is as follows:

type method-name(parameters-list) throws exception-list
{

      //body of method

}

 

The exception-list is a comma separated list of exceptions that the method might throw. Except the sub classes of Error and RuntimeException classes all other exceptions (checked exceptions) must be mentioned explicitly with the throws keyword. Otherwise, it will lead to compile-time errors.

 

Let’s see a sample program which demonstrates the use of throws keyword:

class ArrayException
{
	static void myMethod() throws ArithmeticException
	{
		throw new ArithmeticException("Testing throws");
	}
	public static void main(String[] args)
	{
		try
		{
			myMethod();
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}

 

Observe that the method myMethod() does not handle ArithmeticException. It throws the exception to its caller (main method) which in turn handles the exception. We can throw multiple exceptions using the throws keyword.

 

finally Keyword

 

The statements in finally  block are guaranteed to be executed irrespective of whether an exception raises or not. House keeping code like closing the connection to a file or database can be written in a finally block as it always executes.

 

Let’s see an example program which demonstrates the use of finally keyword:

class FinallyDemo
{
	public static void main(String[] args)
	{
		try
		{
			int a[] = {1,2,3,4,5};
			System.out.println("Value is: " + a[4]);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		finally
		{
			System.out.println("Guaranteed to execute");
		}
	}
}

 

Output of the above program is:

 

Value is: 5
Guaranteed to execute

 

Let’s modify the above program so that an exception is raised:

class FinallyDemo
{
	public static void main(String[] args)
	{
		try
		{
			int a[] = {1,2,3,4,5};
			System.out.println("Value is: " + a[8]);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		finally
		{
			System.out.println("Guaranteed to execute");
		}
	}
}

 

Output of the above program is:

 

java.lang.ArrayIndexOutOfBoundsException: 8
Guaranteed to execute

 

Note that in both cases the statement inside finally block got executed.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

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