AppDividend
Latest Code Tutorials

Java Throw Exception: A Brief Guide

First of all, we need to know about what is an Exception. An exception is a kind of error at the runtime. There are a lot of exceptions in Java-like ArithmeticException, NullPointerException, ArrayIndexOutOfBound Exception, etc.

Suppose we are dividing a number by zero, it will not return any compilation error, but it will return runtime error, and it’s under ArithmeticException. Again, if we add a further element in Array beyond its capacity, then it returns the ArrayIndexOutOfBound Exception. Almost every other method in the java library or even user-defined may throw an exception or two.

Java Throw Exception

The throw keyword in Java is used to explicitly throw an exception from a method or any code block. The caller must catch the exceptions. Compiling will fail if you do not handle the Exception in the try-catch block.

We can define our own rules or conditions and throw an exception explicitly using the throw keyword. For example, we can set a condition like dividing by 5 will return ArithmeticException, and we can throw it using the throw keyword. We can also use the throw keyword in Custom Exception.

Syntax of throw keyword

throw Instance;

Now, see the following code.

throw new ArithmeticException (“divided by zero”);

Let’s take a simple example to understand throw an exception better way.

// ThrowExceptionExample.java

class ThrowExceptionExample
{
  static void valid(int age)
  {
	  if(age<18)
	  {
		  throw new ArithmeticException("Not Age to vote.");
	  }
	  else
		  System.out.println("You are welcome to vote.");
  }
  public static void main(String []er )
  {
	  valid(13);//throws example
	  valid(18);//does not throw example 
	  
  }
}

See the following output.

T_notValid

The execution flow of a program stops after the throw statement is executed. First, the nearest try block is checked to see if the program has a catch statement that matches the exception type.

If it finds a match, it transfers the control to the statement; else next try block is checked. After that, it’ll be checking if there is no match. Finally, if no match is found in the whole program, the default halter will halt the program.

Let’s see an example regarding this to understand this better.

// ExceptionExample.java

import java.io.*;
import java.util.*;

class InvalidStringException extends Exception
{
	public String toString()
	{
		return "String is ODD";
	}
}
class MyString
{
	MyString(String s) throws InvalidStringException
	{
		int l=s.length();
		if(l%2==0)
		{
			System.out.println(s);
		}
		else
		{
			throw new InvalidStringException();
		}
	}
}
class ExceptionExample
{
	public static void main(String []er)
	{
		Scanner sc=new Scanner(System.in);
		System.out.println();
		//entering a string 
		String a=sc.next();
		try
		{
			MyString m=new MyString(a);
			
		}
		catch(InvalidStringException e)
		{
			System.out.println(e);
		}
	}
}

See the following output.

Java throw keyword

What is throws keyword in Java

The throws keyword in JAVA is used to declare that the method may throw one or some exceptions. The caller must catch the exceptions.

Compiling will fail if you do not handle the Exception in a try-catch block. But almost every other method in the java library or even user-defined may throw an exception or two.

What is the difference between throw and throws

throw
throws
It is used to create the new Exception object and throw it It is used in the method definition to declare that the risky method is being called.
Using a throw keyword, you can declare only one Exception at a time Using the throws keyword, you can declare multiple exceptions simultaneously.
Example:

throw new IOException(“can not open connection”);

Example:

throws IOException, ArrayIndexBoundExceptiThat’sat’s it for this example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.