Difference Between throw and throws keyword in Java

In the below let me write throw and throws in details Furthermore I will discuss the difference between the two keywords in java.

Throw Keyword Simplified in Java

Exceptions occur when some predefined exceptional events occur in a program. Sometimes it is ok to handle predefined Exceptions but sometimes it is reasonable and convenient to define our Exceptional events. The throw keyword is used to create our own and new Exception which can be thrown to the catch block. In java, throw keyword is used by which the user can throw an exception of his/her own, instead of the automatic Exception object generated by java during runtime.

Below steps happens when we throw an exception:

  1. The Exception object itself is created, in the same way, that any java object is created on the heap with a new keyword. In general, it is not there under normal program execution and the constructor is called for that object. The object is returned from that method.
  2. The current path of the Execution (the original one that was not continued) is stopped and the handle for the Exception object is ejected from the current context.
  3. At this point the Exception handling mechanism takes over and begins to look for an appropriate place is the Exception handler, whose job is to resolve from the issue.
  4. by throwing we can send information about the issue into a larger context by creating an object representing our information and throwing it out of our current context. This is called throwing an Exception.
  5. This throws the Exception allows us in the current context, abdicate responsibilities and it is handled somewhere else.

Once we throw the handle of the Exception, all further catch clauses for the same try block are ignored and throw causes the Exception to go to the next higher context for handling. Also every information about the Exception is preserved. So that the handle at the higher context that catches the specific Exception type can Extract all information from the Object.
The syntax is :


Exception e =new Exception();
throw e;
//e is new Throwable subclass
 

Any object of type throwable can be thrown. Exceptions also accept a message for themselves.


throw new Exceptioon("Here is my Message");
 

Having Exceptions with custom message increases the readability of the application. It also helps in debugging.
Rethrowing an Exception:
It is also possible to rethrow an Exception if we want that we just caught using catch block. As in the catch block, we simply have the handle of the current Exception, we can rethrow.

catch(Exception e)
           {
               System.out.println("An error has occured");
               throw e;
           } 

An example of throw:

public static void divide(int x,int y){
try{
if(y==0)
throw new Exception("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
catch(Exception e)
{
}
} 

The above code will throw an Exception if the divisor is zero.

How a user can generate his Exception using throw:

public static void main(String args[])
{
try{
myDemo();
}
catch(Exception e)
{
System.out.println("Exception thrown by MyDemo is caught here");
}
static void MyDemo()
{
try{
throw new InterruptedException("An Interrupted Exception Occurred");
}
catch(InterruptedException e)
{
throw e;
}
}

Pure user-defined Exception:
Beside regular java Exceptions, we can create our Exception called custom exception. They make the code flexible and manageable.
we need to create an Exception class:

public class MyDivisionException Extends Exception
{
//create a parameterized constructor
public MyDivisionException(String message)
{
super(message);
}
}

then the below code:

public static void divide(int x,int y){
try{
if(y==0)
throw new Exception("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
catch(Exception e)
{
}
}
 

can be modified as:

public static void divide(int x,int y) throws MyDivisionException{ 
if(y==0)
throw new MyDivisionException("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
} 

How to rethrow of Exception preserve the information about the Exception:
If we rethrow the current Exception, the information about the Exception is preserved i.e the origin of the Exception instead of the place where we rethrew it. If we want to know the new stack trace information we can use fillInStackTrace() which returns an Exception object that is created with old Exception by appending the current stack information.

public class MyRethrowExample{
     public static void main(String []args) throws Throwable{
        try{
            methodOne();
        } 
        catch(Exception e)
        {
            System.out.println("Caught in main()");
            e.printStackTrace();
         }
    }
    public static void methodOne() throws Throwable{
        try{
            methodTwo();
        }
        catch(Exception e)
        {
             System.out.println("Caught in methodOne()");
             e.printStackTrace();
            // e.fillInStackTrace();
             throw e;
        }    
    }
    public static void methodTwo() throws Exception{
             System.out.println("Originating at methodTwo()");
             throw new Exception("Thrown from methodTwo()");
     }
 }
 

the output of the code:
$javac MyRethrowExample.java
$java -Xmx128M -Xms16M MyRethrowExample
Originating at methodTwo()
Caught in methodOne()
Caught in main()
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:27)
at MyRethrowExample.methodOne(MyRethrowExample.java:15)
at MyRethrowExample.main(MyRethrowExample.java:5)
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:27)
at MyRethrowExample.methodOne(MyRethrowExample.java:15)
at MyRethrowExample.main(MyRethrowExample.java:5)
Explanation:
the stack trace always remembers it’s the original point of origin, no matter how many times the exception is rethrown.

Once we enable the e.fillInStackTrace(); the output is :

$javac MyRethrowExample.java
$java -Xmx128M -Xms16M MyRethrowExample
Originating at methodTwo()
Caught in methodOne()
Caught in main()
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:26)
at MyRethrowExample.methodOne(MyRethrowExample.java:14)
at MyRethrowExample.main(MyRethrowExample.java:4)
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodOne(MyRethrowExample.java:20)
at MyRethrowExample.main(MyRethrowExample.java:4)
Explanation:
Because of fillInStackTrace() , new point of origin of Exception,The class Throwable must appear in the Exception specification for methodOne() and main().fillInStackTrace() produces handles to a throwable object .

throwable is the base class of Exception but it may so happen that we may get an object that is throwable but not an Exception,so the handler of Exception in main() may miss it.To make sure everything is in order,the compiler forces an Exception specification for throwable.

Throws Keyword Simplified in Java

Throws keyword is used to indicate that a method may throw one or more exceptions that are defined in the method header or signature. For cases where the exception handling is mandatory for those cases, the method must announce the throws clause in the definition. The caller of the method may choose to handle that exception or can throw it again. So handling this exception is optional.

Handling every exception is a very tedious job and may hinder the coder’s output. If we do not handle the exception in a try-catch block, we can throw the exception to the calling method. If either of the two is not done compiler will throw an error. The idea behind enforcing this rule is that as a programmer, we should aware that a piece of code be risky and throws some exceptions.
By throws keyword, a designer of a method may throw any number of exceptions separated by comma(,). By throwing an exception, we can propagate and handle the exception is somewhere else in the code.

The syntax for throws is given as :

method(argumentList) throws ExecptionType1,ExceptionType2,....,ExceptionTypeN
{
} 

like:

void processMyArray(int A[])throws NullPointerException,ArrayIndexOutOfBoundsException,ArrayStoreException
{
} 

An Example:

pulic static void divide(int x,int y)throws Exception{
if(y==0)
throw new Exception("The divisor can not be Zero");
int z=x/y;
} 

In the above code, there is no try-catch block to safeguard the potential risky code. Instead, we throw an exception from here and the signature of the method says it can throw an Exception. In case if there is any Exception is created, the object will be propagated to the calling method. The calling method (maybe main). The calling method should handle the exception.

public static void callerMethod()
{
try{
divide(10,0);
}
catch(Exception e)
{
}
}
 

The caller method does not handle the Exception and may choose to throw it again.

public static void callerMethod() throws Exception
{
divide(10,0);
} 

In cases, where some states in the body of a subroutine that can throw the exception by using throw statement(throw an exception directly), like our previous divide by zero examples, or it could be a call to a method that can throw an exception.

In both cases, the exception must be handled. However, it is good to handle the exception for any exception that is not a subclass of Error or RuntimeException. Exceptions that require mandatory handling generally represent conditions that are outside the control of the program.

Besides both serve different purposes. The difference table is given below:

Sl Nothrowthrows
1a throw is used to create a new Exception object and throw it.It is used in method definition to declare that a risky method is being called and

the method may throw the specified exception.

2Using throw we can only throw one Exception typeusing throws we can declare multiple Exceptions
3Example-throw new IOException (“Can not open Connection”);Example- throws IOException, ArrayIndexBoudException

An example of throws and throws of custom Exception.

//custom exception class

 class MyFirstException extends Exception {
public MyFirstException() {super();}
public MyFirstException(String msg) {super(msg);}
}
 class MySecondException extends Exception {
public MySecondException() {super();}
public MySecondException(String msg) {super(msg);}
}
 class MyFisrtSubException extends MyFirstException {
	 public MyFisrtSubException() {super();}
	 public MyFisrtSubException(String msg) {super(msg);}
	 }
//save it to MyFirstException.java

The actual implementation of the code:



public class MyExceptionThrowTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
      int x;
		try{
			x =Integer.parseInt(args[0]);
			}
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println("specify an argument");
			return;
		}
		catch(NumberFormatException e)
		{
			System.out.println("specify an integer argument");
			return;
		}
		myFirstMethod(x);
	}

	private static void myFirstMethod(int x) {
		// TODO Auto-generated method stub
		try {
			mySecondMethod(x);
		}
		catch(MyFirstException e) {
			if(e instanceof MyFisrtSubException)
			{
				System.out.println("MyFirstSubException");
			}
			else
			{
				System.out.println("MyFirstException");
				System.out.println(e.getMessage());
				
			}
				
		}
	}

	private static void mySecondMethod(int x) throws MyFirstException {
		int res;
		try {
		System.out.println("x"+x);
		res=myThirdMethod(x);
		// TODO Auto-generated method stub
		}
		catch(MySecondException e)
		{
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("\n");
		}

}

	private static int myThirdMethod(int x) throws MyFirstException, MySecondException {
		// TODO Auto-generated method stub
		switch (x) {
		case 0: throw new MyFirstException("No input");
		case 1: throw new MyFisrtSubException("no input at second");
		case 50: throw new MySecondException("input too high");
		default: x=x*x;
		}
		
		return x;
	}
}


The output:
if no argument is given – the console message-specify an argument
if the argument is type float like 4.3- the console message-specify an integer argument
if the argument is type integer and value is 50- the console message-x50
input too high

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on [email protected]

Write A Comment