Difference between Throw and Throws in Java

In Java,” throw” and” throws” are keywords used in exception handling, and they serve different purposes. Let’s deep dive into Java throw vs throws.

Java Throw

The “throw” keyword explicitly throws an exception within a system or block of code. When you throw an exception using” throw,” you’re flagging that a commodity exception or incorrect value has passed. You want to propagate that exception up the call stack to be handled by an applicable exception handler (e.g., a catch block).

It is also an illustration of using” throw” to produce and throw a custom exception.

java public void peak( int tip, int divisor){ 
if( divisor ==  0){
throw new
ArithmeticException("FirstCode says  Division by zero isn't allowed.");
int result =  tip/ divisor;

Rest of the law. If the divisor is zero, an” ArithmeticException” is created and thrown, indicating that a division by zero error has occurred.

Java Throws

The” throws” keyword is used in a system prototype to specify that the system may throw certain exceptions. It’s used to declare exceptions that might be propagated out of the system, allowing the programmer to be aware of them and either handle them or propagate them further. Also, it is an illustration of using” throws” in a system protestation in Java;

public void readFile( String filePath) throws FileNotFoundException{
/ law to read a train In this illustration,
}

The” readFile” system is declared to throw a” FileNotFoundException ” potentially. It informs the frequenter that they should be prepared to handle this exception or propagate it further up the call stack.

Java throw

The throw keyword in Java explicitly throws an exception from a system or any code block. We can throw either a checked or an unchecked exception. The adventure keyword is substantially used to throw custom exceptions.

Syntax of Java throw

throw Instance

throw new
ArithmeticException(“/ by zero”);
But this exception, i.e., the Instance must be of type Throwable or a class of Throwable.

An Exception is a subclass of Throwable, and user-defined exceptions generally extend the Exception class. Unlike C, data types such as int, housekeeper, float, or non-throwable classes cannot be used as exceptions.

The program’s exception-handling flux stops immediately after the adventure statement executes, and the nearest enclosing pass block is checked to see whether it has a catch statement that matches the exception type. However, control is transferred to that statement; otherwise, the enclosing pass block is checked, and so on, until a match is found. If no matching catch is set up, the dereliction exception educator will also halt the program.

Example of Java Throw

/ Java program that demonstrates the use of adventure
 class Throw
Excep{ static void FirstCode() 
{
try{ 
throw new NullPointerException(" rally");
{
catch( NullPointerException e){
(" Caught inside FirstCode).");
 throw e;// rethrowing the exception
 public static void main( String args())
 Try{
 FirstCode();
}
 catch( NullPointerException e){
(" Caught in main.");
}
}

Caught inside FirstCode().
Caught in main.

Illustration of the program

/ Java program that demonstrates
 the use of throw
 class FirstCode{
 public static void main( String() args)
{
( 1/ 0);
}

 Exception in thread" main"
java.lang.ArithmeticException
/ by zero

Java throws

Throws is a keyword in Java used by a system to indicate that this system might throw one of the listed types of exceptions. The programmer of these styles has to handle the exception using a try-catch block.

Syntax of Java Throws

typemethod_name( parameters)
throwsexception_list
It is a comma-separated list of all the exceptions a system might throw.

In a program, if there’s a chance of raising an exception, the compiler always warns us about it, and we should compulsorily handle that checked exception. Otherwise, we will get a collect-time error stating that unreported exception XXX must be caught or declared to be thrown.

To help with this collection time error, we can handle the exception in two ways:

  • By using a pass catch
  • By using the throws keyword

We can use the throws keyword to delegate the responsibility of exception handling to the framework ( It may be a system or JVM). Also, the frequent system is responsible for handling that exception.

Java throws samples

Illustration

class FirstCode{
public static void main( String() args)
{
( 10000);
(" FirstCode");
}
}

Unreported error exception InterruptedException: needs to be thrown or caught

In the program below, we’re getting a collect time error because if the main thread is going to sleep, there’s a chance of an exception; other threads get the chance to execute the primary () system, which will result in an InterruptedException.

Illustration of the throws in Java

/ Java program to illustrate throws 
class FirstCode{
public static void main( String() args) throws InterruptedException
{
( 10000);
(" FirstCode");
}
}

Output:

FirstCode

In the program below, we handled the InterruptedException by using the throws keyword, and we will get the output as Hello Geeks

Illustration

class ThrowsExecp{ 
static void FirstCode() throws IllegalAccessException
{
(" Inside FirstCode()."); 
throw new IllegalAccessException(" rally");
}
 public static void main( String args())
{
try{ 
FirstCode(); 
}
catch( IllegalAccessException e){
(" caught in main.");
}
}
}

Output:

InsideFirstCode().
caught in main.

Essential Points to Flashback about the throws Keyword in Java

The throws keyword is demanded only for checked exceptions, and the operation of the throws keyword for unbounded exceptions is pointless. This keyword is required only to move the compiler, and its operation doesn’t help prevent abnormal program termination. The throws keyword informs the interpreter about the exception.

Difference between throw and throws in Java

Let’s discuss the distinctions between Java’s Throw and Throws. The “throw” keyword explicitly throws an exception. It is followed by an instance of an exception or an expression that results in an exception.

A “throws” in a method signature indicates that the method might throw one or more exceptions. It’s a way of declaring the exceptions that a process can potentially throw, allowing the caller to handle or propagate those exceptions.

The “throw” is used to actually throw an exception, while “throws” is used in a method declaration to specify the exceptions the method might throw.

Conclusion

Throw is used to throw an exception when an error or an exceptional situation occurs. The throws clause is used in a method’s declaration to specify which checked exceptions the method might throw.

The choice between these two keywords depends on your code’s specific requirements. Throw is used when you want to raise an exception actively, and you use throws when you want to declare the potential exceptions that a method may throw, but leave it to the calling code to handle them.

To ensure robust error handling in Java programs, it’s essential to handle exceptions properly using try-catch blocks or propagate them up the call stack using throws declarations.

Leave a Reply

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