Exception (middle) Create custom exceptions, throw, throws keywords throw exceptions

Article Directory

  • foreword
  • 1. Create a custom exception
  • 2. Throw an exception in the method
    • 1. Use the throw keyword to throw an exception
    • 2. Use the throws keyword to throw an exception
  • Summarize

Foreword

This article introduces the creation of custom exceptions in Java, so that we can create an exception by ourselves to deal with basic exceptions that do not exist in the Java API. The throw keyword throws an exception, and the throws keyword throws an exception, which is another way of throwing an exception different from the try-catch statement.

1. Create a custom exception

Create a custom exception: Create one yourself to deal with the exception that can be fed back that does not meet the project requirements or reality, and deal with the situation where there is no basic exception in the Java API.

Syntax:

class custom exception class extends existing exception class{
    public custom exception class(){
        //Create a construction method, call the parent class construction method through the super keyword, and feedback new exceptions that do not meet
        super();
    }
}

Example:

When serving a person in an unmanned restaurant, if the customer is not a person but an animal, this exception needs to be thrown, but the basic exception error report in the Java API does not have this exception, and we need to customize an exception.

Create a NoHumansException exception class to deal with the exception of this unmanned restaurant:

public class NoHumansException extends Exception{
\t
public NoHumansException(String message) {
//Create a construction method, call the parent class construction method through the super keyword, and feedback new exceptions that do not meet
    super(message);
}
}

Calling this exception in the project:

public class Demo {
public static void main(String[] args) {
try {
String customer = "monkey";
if(!customer.equals("human")) {
                //The NoHumansException exception class created by instantiating the throw keyword
throw new NoHumansException("There are non-human customers:" + customer);
}
System.out.println("serve");
} catch (NoHumansException e) {
//Output the exception caught in the try code block, related exception content, error location
e.printStackTrace();
}
}
}

Output:

Summary:

Use a custom exception step:

(1) Create a custom exception.

(2) Throw an exception object through the throw keyword in the method.

(3) If the exception is handled in the method currently throwing the exception, you can use the try-catch statement block to catch and handle it, otherwise, use the throws keyword to indicate the exception to be thrown to the method caller at the declaration of the method, and proceed to the next step One step operation.

(4) Catch and handle the exception in the caller of the abnormal method.

2. Throw an exception in the method

Before:If an exception may occur in a certain method, if you do not want to handle this exception in the current method, you can use the throw and throws keywords to throw an exception in the method.

1. Use the throw keyword to throw an exception

Definition: The throw keyword is usually used in the method body and throws an exception object.

Syntax:

throw new exception type (error content);

Features:

(1) When the program runs to the throw statement, immediately stop executing the following statement (the statement in the code block).

(2) After an exception is thrown through throw, if you want to catch and handle the exception in the upper level code, you need to use the throws keyword in the method of the thrown exception.

(3) If you want to catch the exception thrown by throw and the feedback is in the console, you must use the try-catch statement block.

Example:

When counting the number of people, the number of people is a value greater than zero. When the value of the number of people is negative, an error should be reported. Although no error will be reported automatically during the running process, we can use the throw keyword to throw to realize the error report.

public class ThrowDemo {
public static void main(String[] args) {
        //Define the number of people as a count object
int count = -100;
try {
if(count < 0) {
//When the number of people is less than zero, throw this exception and terminate the program in the try code block
throw new ArithmeticException("Number of people is negative" + count);
}
System.out.println("The number of people currently counted is:" + count);
} catch(Exception e) {
//Call the printStackTrace() method to feed back the nature, content, and location of the thrown exception in the console
e.printStackTrace();
}
}
}

Output:

2. Use the throws keyword to throw an exception

Definition: The throws keyword is usually used when declaring a method to specify the exceptions that may be thrown by the method (mostly to warn of exceptions in this method).

Syntax:

public void method() throws exception type 1, exception type 2, ..., exception type n{

}

Features:

(1) After using the throws keyword to throw an exception to the upper level, if you don’t want to handle the exception, you can continue to throw it up, but the code that will eventually handle the exception .

(2) Multiple exceptions can be separated by commas,

(3) If it is Error, RuntimeException or their subclasses, you can declare the exception to be thrown without using the throws keyword, the compilation can still pass smoothly, but it will be thrown by the system at runtime .

Example:

public class ThrowsDemo {
\t
    //When defining the show() method, use the throws keyword to throw an exception
public static void show() throws ArithmeticException,Exception{
for(int i = 0;i<10;i ++ ) {
int b = 1/0;
            //Operation here, the divisor cannot be zero, an exception occurs
}
}
\t
public static void main(String[] args) {
//try-catch statement feedback processing exception
        try {
show();
} catch (Exception e) {
// Feedback abnormal information in the console
            System.out.println("Exception: Divisor cannot be zero!");
System.out.println("Please programmers solve it as soon as possible!");
e.printStackTrace();
}
}
}

Output:

It can be seen from this that whether it is throw, throws, or try-catch statements, they do not have the ability to correct bugs. They are just auxiliary tools for programmers to detect, refine, and modify BUG. The specific BUG needs us to deal with it by ourselves, don’t be lazy.

Summary

This blog introduces the creation of custom exceptions, the use of throw and throws keywords in exceptions. If you have any doubts or supplements or corrections in this article, please leave a message in the comment area, blogger Will reply promptly.