Difference Between Throw And Throws In Java

Within the Java programming language, there exist two specific keywords, namely throw and throws, which play a crucial role in the process of exception handling by indicating and declaring exceptions.

Java throw Keyword

In Java, the "throw" keyword is employed to intentionally raise an exception, disrupting the regular program flow by directing control to the closest catch block capable of managing the raised exception. If an exception arises within a method, the method generates an exception object and initiates its throwing using the "throw" keyword.

To read more Java throw Exception

Example: Use of throw Keyword

Example

Example

public class Main {

	// defining a method

	public static void checkNum(int n) {

		if (n < 1) {

			throw new ArithmeticException("\nNumber is negative, cannot calculate square");

		} else {

			System.out.println("Square of " + n + " is " + (n * n));

		}

	}

	// main method

	public static void main(String[] args) {

		Main obj = new Main();

		obj.checkNum(-3);

		System.out.println("Rest of the code..");

	}

}

Output:

Output

Exception in thread "main" java.lang.ArithmeticException: 

Number is negative, cannot calculate square

	at Main.checkNum(Main.java:5)

	at Main.main(Main.java:13)

Explanation

Within the Main class, there is a method called "checkNum" which accepts an integer as a parameter. Inside this method, there is a validation to determine if the provided number is below 1. In such a case, an ArithmeticException is raised with a specific message stating that the number is negative, and therefore, its square cannot be computed. Conversely, if the number is non-negative, the method proceeds to compute and display the square of the input number.

Within the main function, a new object of Main is instantiated, and the "checkNum" function is invoked with a negative integer (-3) as its parameter. Due to the negative input, the function raises an ArithmeticException. As this exception is not handled within the main function, the program halts abruptly following the display of the exception message.

Consequently, the code following the statement "Rest of the code." will not be executed. The provided code demonstrates the utilization of the "throw" keyword in Java to intentionally raise an exception when specific conditions are satisfied, allowing the manipulation of program flow according to dynamic circumstances.

Java throws Keyword

Conversely, the "throws" clause within method signatures is employed to signify that the method has the potential to throw specific types of exceptions while it runs. The method itself does not trigger the exception but rather acknowledges that it has the capability to throw exceptions of designated types, thereby notifying the caller to manage them accordingly.

To read more Java throws Keyword

Example: Use of throws Keyword

Example

Example

public class Main {

	// defining a method

	public static int divideNum(int m, int n) throws ArithmeticException {

		int div = m / n;

		return div;

	}

	// main method

	public static void main(String[] args) {

		Main obj = new Main();

		try {

			System.out.println(obj.divideNum(45, 0));

		} catch (ArithmeticException e) {

			System.out.println("Number cannot be divided by 0");

		}

		System.out.println("Rest of the code..");

	}

}

Output:

Output

Exception caught: Number is negative, cannot calculate square

Program continues...

Explanation

Within the Main class, there is a function called "divideNum" which requires two integer inputs and outputs the quotient of dividing the first input by the second. This function is specified with a "throws ArithmeticException" statement, signaling the possibility of throwing an ArithmeticException in case the second input is zero, which would lead to a division by zero exception.

Within the main function, a new object of the Main class gets instantiated, and the method "divideNum" is executed within a try-catch block. In case an ArithmeticException is raised during the execution of the method, it is captured by the catch block, which displays a notification stating that division by zero is prohibited.

In Java, even if an exception is encountered, the program will proceed with executing the rest of the code and output " Rest of the code ." to the console. This code serves as an illustration of utilizing the "throws" keyword to indicate possible exceptions within a method declaration and managing these exceptions through a try-catch block.

Example: Use of throw and throws Keyword

Example

Example

public class Main {

	// creating a user-defined function that raises an ArithmeticException

	static void method() throws ArithmeticException {

		System.out.println("Inside the method()");

		throw new ArithmeticException("Throwing ArithmeticException");

	}

	// main method

	public static void main(String args[]) {

		try {

			method();

		} catch (ArithmeticException err) {

			System.out.println("Caught in main() method");

		}

	}

}

Output:

Output

Inside the method()

Caught in main() method

Explanation

Within the Java program shown previously, there is a Main class that encompasses a static method labeled "method" in addition to the main method. The "method" is defined with the "throws ArithmeticException" provision, signaling the potential occurrence of an ArithmeticException while it runs. Inside "method", a message is displayed on the console followed by the deliberate throwing of an ArithmeticException.

Within the main function, the "method" is called inside a try-catch block to handle any ArithmeticException that might occur during its execution. When the program runs, the message "Inside the method" is displayed on the console after the "method" is invoked.

Following that, as anticipated, the ArithmeticException is triggered and handled by the catch block within the main function, causing the output of the message "caught in main function".

The following code snippet demonstrates the utilization of the "throws" keyword in a method signature to specify possible exceptions and the handling of these exceptions through try-catch constructs in the Java programming language.

Java throw Vs. throws

Characteristics throw throws
Definition Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code. Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.
Declaration It is used inside a method or block. It is used with method signature.
Usage Type of exception using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only. Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only.
Purpose It triggers the creation and throwing of an exception. It informs the caller of the method about possible exceptions may occur.
Syntax throw new ExceptionType("message"); public void myMethod() throws IOException
Number of Exceptions It can throw only one exception at a time. It can declare multiple exceptions separated by commas.
Followed By An instance of Throwable (or subclass). One or more exception classes (checked exception only).
Internal Implementation We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions. We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws IOException, SQLException.

Important Points to Remember

throw keyword

  • It throws an exception object.
  • It is used when we want to manually raise an exception.
  • It is used inside method.

For example,

Example

throw new IllegalArgumentException("Invalid input");

throws keyword

  • It declares that a method might throw one or more exceptions.
  • It is used when method contains code that may throw a checked exception , and we want the caller to handle it.
  • It is used with method signature.

For example,

Example

public void readFile() throws IOException {

    // code that might throw IOException

}

Conclusion

In summary, having a clear comprehension of the contrast between "throw" and "throws" in Java is crucial for efficient exception handling. Although both terms are important in handling exceptions, they have specific roles and applications in different scenarios. The "throw" keyword is employed to explicitly raise exceptions within methods or code blocks, interrupting the regular program execution and shifting control to the closest catch block.

Conversely, the "throws" keyword is utilized in method declarations to specify the kinds of exceptions that a method could potentially throw while running, offering a way for the caller to manage potential exceptions effectively.

Java Throw and Throws MCQ

  1. Which of the following statements is true about the throw keyword in Java?
  • It is used to declare exceptions that a method may throw.
  • It is used to handle exceptions within a method.
  • It is used to throw an exception explicitly from a method or block of code.
  • It is used to catch exceptions thrown by other methods.

Explanation: The throw keyword is used to throw an exception manually from a method or block of code in Java.

  1. Which type of exceptions can be thrown using the throw keyword in Java?
  • Only unchecked exceptions.
  • Only checked exceptions.
  • Both checked and unchecked exceptions.
  • Only custom exceptions.

Explanation: The throw keyword can be used to throw both checked and unchecked exceptions in Java, but it's mainly used for propagating unchecked exceptions.

  1. In Java, where is the throws keyword used?
  • Inside a method to declare an exception to be thrown.
  • Inside a catch block to handle exceptions.
  • Inside a finally block to perform cleanup actions.
  • Inside a try block to monitor code for exceptions.

Explanation: The throws keyword is used in the method signature to declare that the method may throw a specific type of exception.

  1. Can a method use both throw and throws keywords in its definition?
  • Yes, but only if the method is static.
  • Yes, if the method is declared as final.
  • Yes, but only if the method is defined in an abstract class.
  • No, it's either one or the other, not both.

Explanation: A method can either use the throw keyword to throw an exception or the throws keyword to declare that it may throw an exception, but not both simultaneously.

  1. What is the purpose of the throws keyword in Java
  • To catch exceptions thrown by other methods.
  • To handle exceptions within a method.
  • To throw exceptions explicitly from a method.
  • To declare that a method may throw a specific type of exception.

The throws keyword is utilized in the method declaration to specify that the method has the potential to throw a particular type of exception while it is running.

Input Required

This code uses input(). Please provide values below: