×

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code recovery and debugging simpler.

The notice that comes with the exception contains a description of the error. These anomalies could be caused by user inputs, the server, etc.

Java's throw keyword allows us to throw either verified or unchecked exceptions. It mostly serves as a custom exception thrower. Custom exceptions will be covered later in this section. Additionally, we can use the throw keyword to specifically throw an exception and establish our own set of circumstances. For instance, dividing a number by another number may result in the throwing of an ArithmeticException.

Syntax of Throw keyword in Java:

toss Instance, that is.

Examples of Throw Keyword

Example 1: Throwing Unchecked Exception

public class TestTh1 {   
    //function to determine whether or whether a person is entitled to vote
    public static void valid (int years) {  
        if(years<18) {  
            //Mathematical exception if ineligible to vote
            throw new ArthExcp ("One is not elligible to cast a ballot");
        }  
        else {  
            System.out.println("One can eligible to vote");
        }  
    }  
    //main method  
    public static void main (String s []) {
        //function is called
Valid(15);
        System.out.println("rest of the code...");
  }    
}    

Output:

One is not eligible to cast a ballot

An unchecked exception is thrown by the code above. Like checked exceptions, user defined exceptions can also be thrown.

NOTE: A method must handle or declare an unchecked exception it throws in the throws clause.

If a checked exception is thrown using the throw keyword, it must be handled using a catch block or declared in the method's throws declaration.

Example 2: Throwing Checked Exception

Any other exceptions that belong to the Throwable class are checked exceptions.

TestThrow2.java
import java.io. *;  
public class TestTh2 {   
    // function to determine whether or whether a person is entitled to vote
    public static void med () throws FileNotFoundExcp {  


        FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
        BuffReader fileInput = new BuffReader(file);


        throw new FileNotFoundException ();
    }  
    //main method  
    public static void main (String s[]){  
        try  
        {  
med ();
        }   
        catch (FileNotFoundExcp e)   
        {  
e. printStackTra ();
        }  
        System.out.println("rest of the code...");
  }    
}    

Output:

FileNotFoundException
rest of the code...

Example 3: Throwing User-defined Exception

TestThrow3.java


// class depicts a custom exception
class UserDefinedException extends Exception  
{  
    public UserDefinedException (String str)  
    {  
        // calling the parent's function Object () {[native code]} exception
        super(str);
    }  
}  
// Class that references MyException above
public class TestTh3  
{  
    public static void main (String s[])  
    {  
{


            // Print the message from the object MyException
            System.out.println(ude. getMessage ());
        }  
    }  
}   

Output:

This is user-defined exception
the exception caught

Throws Keyword in Java

Declaring an exception in Java requires the throws keyword. The programmer is informed that an exception might happen.

The primary purpose of exception handling is to manage checked exceptions. Programmers are to blame for any unchecked exceptions, such as NullPointerException, because they failed to examine the code before it was utilised.

Syntax of Java throws:

return_type method_name () throws exception_class_name
{  
//method code  
}  

Which exception should be declared?

Ans: merely checked the exception, because:

Unchecked exception: within our power to fix our code.

error: not within our power. For instance, if a VirtualMachineError or StackOverflowError happens, nothing can be done.

Advantages of Java Throws Keyword

Checked Exceptions can now spread (forwarded in call stack).It informs the method's caller with details on the exception.

Examples of Java Throws Keyword

Let's look at an example of a Java throws clause that explains how the throws keyword can propagate checked exceptions.

Testth1.java
import java.io. IOException.
class Testth1{  
  void mn () throwsIOException {
    throw new IOException ("error of the device”) ;//exception is checked
  }  
  void mm () throwsIOException {
mn ();
  }  
  void pp() {
try {
mm ();
} catch (Exception e) {System.out.println("exception handled");}  
  }  
  public static void main (String s[]){  
   Testth1 ob=new Testth1();
ob. pp ();
   System.out.println("flow is normal...");
  }  
}  

Output:

exception handled
flow is normal...

Rule: If a method is being called that declares an exception, the exception must either be caught or declared.

There are two cases:

Case 1: Deal with Exception Try-catch block usage

Regardless of whether the exception happens during the program or not, if it is handled, the function will execute without problem.

Testthrows2.java
import java.io. *;  
class Mm {  
 void med () throwsIOException {
  throw new IOException ("error of devie");
 }  
}  
public class Testth2{  
   public static void main(String s[]){  
    try{  
     Mm m=new Mm ();
     m.med ();
    }catch(Exception e) {System.out.println("exception is handled");}     


    System.out.println("flow is normal...");
  }  
}  

Output:

exception is handled
       flow is normal...

Case 2: Declare Exception

  • If the exception is declared, the function will run without a problem if it doesn't happen.

Let's look at some samples for each case.

a) If the exception doesn't happen

Testthrows3.java
import java.io. *;  
class Mm {  
 void med () throwsIOException {
  System.out.println("operation performed by the device is done");
 }  
}  
class Testth3{  
   public static void main (String s []) throwsIOException {//exception is declared
     M m=new Mm ();
Mm.med ();


    System.out.println("flow is normal...");
  }  
}  

Output:

device operation performed
       normal flow...

B) If exception occurs

Testthrows4.java
import java.io. *;  
class Mm {  
 void med () throwsIOException {
  throw new IOException ("error of the device");
 }  
}  
class Testthrows4{  
   public static void main (String s[])throws IOException {//exception is declared
     Mm m=new Mm ();
     m.med ();
    System.out.println("flow is normal...");
  }  
}  

Output:

Exception in Thread

Unchecked Exceptions:

Rather than being checked during compilation, these are checked at runtime.

Think about the ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException, etc. as an example.

Checked exceptions are those that are reviewed during compilation. Examples include IOException, InterruptedException, etc.

Unchecked exceptions are something we rarely must deal with. The reason for this is that programming errors could result in unchecked exceptions. Furthermore, a good strategy is to correct them rather than handle them.

Differences between Throw and Throws:

In everyday speech, the sole distinction between "throw" and "throws" is tenses. However, these two are significantly different from one another and are employed for a variety of activities in the computer language Java. The Java language's exception handling uses the terms throw and throws.

While throws is used in the method signature to indicate that this method may throw one of the stated type exceptions, throw is used to explicitly throw an exception from a method or any other block of code. Throw and throws are both concepts related to handling exceptions.

The "Throw" keyword is used to pass a manually constructed exception instance to the JVM, whereas the "throws" keyword is used to pass the burden of handling an exception that occurred in a method to the calling method. Throw and throws are two concepts for handling exceptions, with throw throwing the exception directly from a function or block of code and throws being used in a method's signature.

Point of Use

  • When it is necessary to logically throw an exception, it is utilized. The function signature makes use of the throws keyword. When a function contains statements that could result in an exception, it is used.

Second Exceptions Thrown

  • When the throw keyword is used, an exception is explicitly thrown. You can only make one exception at once. Then, if an exception occurs that matches one of the listed ones, it is thrown right away.

Syntax

  • The syntax of the throw keyword includes the instance of the exception that will be thrown. The instance variable comes after throw in the syntax. The syntax of the throws keyword includes the class names of the exceptions that will be thrown. The names of the exception classes are immediately followed by the syntactic term throws.

Exception

  • The Dissemination of Exceptions The throw keyword cannot propagate checked exceptions. The throws keyword only propagates unchecked exceptions that are not checked. The throws keyword can only propagate checked Exceptions.

Example:

TestThrowAndThrows.java
public class TestThrowAndThrows  
{  
    // the creation of a user-defined method that throws an ArithmeticException
    static void method () throws ArithmeticException  
    {  
        System.out.println("Inside the med ()");
        throw new ArithmeticException ("throwing ArithmeticException");
    }  
    //main method  
    public static void main (String s[])  
    {  
        try  
        {  
Med();
        }  
Catch(ArithmeticException e)  
        {  
            System.out.println("caught in main() method");
        }  
    }  
}  

Output:

Exception handled

Related Topics

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.