[JavaSE column 69] throw, throws keywords to achieve elegant exception throwing

Author Homepage: Designer Xiaozheng
About the author: 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction: Vue, SpringBoot, WeChat applet

This article explains the concept of throwing exceptions in Java, demonstrates the usage of throw and throws keywords, and gives sample codes. Throwing an exception refers to explicitly using the throw keyword in the code to throw an exception object. When the code executes to the throw statement, the execution of the current code block will be stopped immediately, and the exception will be thrown to the caller for processing.

Table of Contents

  • 1. What is throwing an exception
  • 2. How to throw an exception
  • Three, throw statement usage
  • Four, throws statement usage
  • Five, throw/throws interview questions
  • 6. Summary

1. What is throwing an exception

In Java, throwing an exception refers to explicitly using the throw keyword in the code to throw an exception object. When the code executes to the throw statement, the execution of the current code block will be stopped immediately, and the exception will be thrown to the caller for processing.

The syntax for throwing an exception is as follows.

throw exception object;

The purpose of throwing an exception is to notify the caller that a specific abnormal situation has occurred, and to require the caller to handle the exception. The caller can use the try-catch statement block to catch and handle the thrown exception, or continue to pass the exception up the call stack.

Throwing an exception can make the exception handling of the program more flexible and standardized. By throwing different types of exceptions, more error information and context can be provided, making error handling more accurate and efficient.

Typically, an exception is thrown when an abnormal condition is detected and normal code execution cannot continue. For example, when the input parameter is illegal, the resource is unavailable, the network connection is disconnected, etc., a corresponding exception can be thrown to notify the caller to handle it.

Tip: Throwing an exception does not mean that the exception will be caught and processed. If there is no suitable try-catch statement block to handle the thrown exception, the exception will continue to pass to the upper call stack. until caught or cause program termination. Therefore, when an exception is thrown in the code, it is necessary to ensure that the exception can be handled appropriately to avoid abnormal termination of the program.

2. How to throw an exception

In Java, exceptions can be thrown using the throw keyword. The specific syntax is throw exception object;, the steps of throwing an exception are as follows, please study carefully.

  1. Create an exception object: First, you need to create a suitable exception object, which can be an instance of an existing exception class or an instance of a custom exception class.
  2. Use the throw keyword to throw an exception: Use the throw keyword to throw the exception object. For example, throw new IOException("Failed to read file");.
  3. Exception handling: When the exception object is thrown, it will be passed to the call stack of the caller. The caller can choose to use the try-catch statement block to catch and handle the exception, or continue to pass the exception to the upper call stack.

Tip: Throwing an exception does not mean that the exception will be caught and handled. Without proper exception handling, the exception will propagate up the call stack until it is caught or causes the program to terminate.

The purpose of throwing an exception is to notify the caller that a specific abnormal situation has occurred and to require the caller to handle the exception. By throwing exceptions, more error information and context can be provided to better locate and handle error conditions. At the same time, throwing exceptions can also make the exception handling of the program more flexible and standardized.

3. Throw statement usage

In Java, the throw statement is used to manually throw an exception. Use the throw statement to interrupt the execution of the current code and throw the specified exception object to the caller. The syntax of the throw statement is as follows, please study carefully.

throw exception object;

Note the following when using the throw statement

4

4

At 4 o’clock, please study hard.

  1. Exception objects must be instances of subclasses of the Throwable class. You can use existing exception classes, such as Exception, RuntimeException, etc., or customize exception classes.
  2. throw statements must appear in method bodies and cannot be used in constructors or static initialization blocks.
  3. throwThe code after the statement will not be executed, so if there are other codes after the throw statement, they will not be executed.
  4. The throw statement is typically used when an abnormal condition is detected that prevents normal code execution from continuing. For example, when the input parameter is illegal, the resource is unavailable, the network connection is disconnected, etc., you can use the throw statement to throw the corresponding exception.

The following is a simple example that demonstrates how to use the throw statement to throw a custom exception, please copy it to the local execution.

public class CustomException extends Exception {<!-- -->
    public CustomException(String message) {<!-- -->
        super(message);
    }
}

public class MyClass {<!-- -->
    public void myMethod(int value) throws CustomException {<!-- -->
        if (value < 0) {<!-- -->
            throw new CustomException("The value cannot be negative");
        }
        // other code
    }
}

In the above example, when calling the myMethod method, if the incoming parameter value is a negative number, a custom exception CustomException and terminate the execution of the method. The caller can use the try-catch block to catch and handle the exception.

4. Throws statement usage

In Java, the throws keyword is used to declare the exceptions that may be thrown by the method. By using the throws keyword in the method declaration, the exception handling responsibility can be handed over to the method , the syntax of the throws statement is as follows.

 modifier return type method name (parameter list) throws exception type 1, exception type 2, ...

Among them, exception type refers to the exception class that the method may throw. Multiple exception types can be declared in the throws statement, separated by commas.

Note the following when using the throws keyword

3

3

At 3 o’clock, please study hard.

  1. The throws keyword can only be used in the method declaration, not inside the method body.
  2. The throws statement in the method declaration is part of the method signature, indicating the type of exception that the method may throw. When calling this method, the exception declared by throws must be handled, either use the try-catch statement block to catch and handle the exception, or continue to pass the exception to the upper call stack .
  3. If the throws keyword is used in the method declaration, but no exception is actually thrown inside the method, then no exception handling is required when calling the method.

The following is an example that demonstrates how to use the throws keyword in the method declaration, please copy and execute it locally.

public void readFile(String filePath) throws FileNotFoundException, IOException {<!-- -->
    // specific code implementation
}

In the above example, the readFile method may throw both FileNotFoundException and IOException. When calling this method, these two exceptions must be handled, otherwise the compiler will report an error.

By using the throws keyword, you can hand over the exception handling responsibility to the caller of the method, so that the code is clearer and more readable, but at the same time, you should also pay attention to the excessive use of throws keyword may lead to poor readability of the code, so it is necessary to weigh the exception handling strategy when using it.

5. Throw/throws interview questions

1. What is the difference between throw and throws keywords?

  • The throw and throws keywords both relate to exception handling, but differ in usage and purpose.
  • The throw keyword is used to manually throw an exception, which is usually used to interrupt the execution of the current code when an error or abnormal condition is detected in the code, and throw the exception object to the caller.
  • The throws keyword is used in the method declaration to declare the exceptions that the method may throw, so that the caller knows that the exception needs to be handled.

2. Under what circumstances is the throw keyword used?

  • The throw keyword is used to manually throw exceptions in code, usually when an error or unusual condition is detected.
  • For example, when the input parameters are illegal, the resources are unavailable, the network connection is disconnected, etc., you can use the throw statement to throw the corresponding exception.

3. What is the function of the throws keyword?

  • The throws keyword is used in the method declaration to declare the exceptions that the method may throw.
  • Its function is to tell the caller that possible exceptions need to be handled, either using the try-catch statement block to catch and handle the exception, or continue to pass the exception to the upper call stack.

4. What is the difference between the exception handling methods of the throw and throws keywords?

  • The throw keyword is used to manually throw an exception, usually handling the exception situation directly in the current code.
  • The throws keyword is used to declare the exceptions that may be thrown by the method, and the responsibility of exception handling is given to the caller of the method.

5. Does the throws keyword require that an exception be actually thrown in the method?

  • uncertain. The throws keyword just declares the exceptions that the method may throw in the method declaration, but it is not mandatory whether the method actually throws an exception.

6. If a method declares a throws exception, how to handle the exception when calling the method?

  • When calling this method, the thrown exception must be handled, either use the try-catch statement block to catch and handle the exception, or continue to use throws< in the upper call stack where the method is called The /code> keyword declares possible exceptions.

6. Summary

This article explains the concept of throwing exceptions in Java, demonstrates the usage of throw and throws keywords, and gives sample codes. In the next blog, I will explain the usage of custom exceptions in Java.

syntaxbug.com © 2021 All Rights Reserved.