×

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 Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.