[2023, learn something new Java-25] How to solve errors in floating-point calculations: strictfp | How to protect sensitive information and improve program reliability and security: transient | Attachment: Introduction to Java Exception Handling Keywords

Review:

  • [2023, learn something new Java-24] abstract modified classes and methods | synchronized synchronization lock | volatile modified member variables | how to ensure the visibility of variables in multithreading? | How to ensure thread safety?
  • [2023, learn something new Java-23] A preliminary understanding of modifiers in Java: static and its functions, native features, final understanding
  • [2023, learn something new Java-22] What is the role of package in Java | Usage of import in Java | Permission modifiers in Java: private, protected, public
  • For more Java series articles, please refer to the blogger’s homepage!

There are always some scenes that we will never forget, and there are always some histories that we will always remember.

–“My Leader, My Group”

Author’s homepage: Light Chaser ♂? ?

Personal profile:

[1] Master of Computer Science

[2] 2022 Blog Star TOP4 in Artificial Intelligence

[3] Alibaba Cloud community invited expert blogger

[4] CSDN-High-quality creators in the field of artificial intelligence

[5] Expected in October 2023 · Prospective CSDN blog expert

  • Infinite progress, follow the light together! ! !

Thank you for liking Favorite? Leave a message! ! !

It is well known that floating-point calculations in Java often have certain errors. In fact, this is because the implementation of floating-point calculations on different platforms is slightly different, resulting in inconsistent accuracy of calculation results. In addition, in Java, do you know how to solve the error in floating point calculation? Do you know how to protect sensitive information, improve the reliability and security of the program, and how to ensure that sensitive information will not be written into the byte stream during serialization? A series of questions such as this may use the keywords described below, such as strictfp and transient. For more details, see this article…

Directory

  • 1. Continued: Modifiers in Java
    • 1.1 strictfp: strictly follow the FP mode
      • 1.1.1 Preliminary introduction
      • 1.1.2 Further description
    • 1.2 transient: instantaneous
      • 1.2.1 Preliminary introduction
      • 1.2.2 Further description
  • 2. In Java, keywords related to exception handling
    • 2.1 try: try to execute, catch: try to catch the exception object, finally: the final block
      • 2.1.1 Preliminary introduction
      • 2.1.2 Further description
    • 2.2 throw: throw
      • 2.2.1 Preliminary introduction
      • 2.2.2 Further description
    • 2.3 throws: throw exception list
      • 2.3.1 Preliminary introduction
      • 2.3.2 Further description

1. Continued: Modifiers in Java

1.1 strictfp: strictly follow the FP mode

1.1.1 Preliminary introduction

strictfp: Indicates that the FP mode is required to be strictly followed, and classes, interfaces, and methods can be modified

When a method is declared with the strictfp keyword, all float and double expressions in the method strictly abide by the restrictions of FP-strict and comply with the IEEE-754 specification.

When the strictfp keyword is used on a class or interface, all code in that class, including initializers and code in nested types, is strictly evaluated.

Strict constraints mean that the result of all expressions must be what IEEE 754 algorithms expect for their operands, in both single and double precision. If you want your floating-point calculations to be more accurate, and the results will not be inconsistent due to different hardware platforms, you can use the keyword strictfp.

1.1.2 Further description

In Java, strictfp is a keyword that can be used to modify classes, interfaces, methods, etc. It is used to make floating-point calculations more accurate and to ensure consistent calculation results on different platforms.

In Java, there are often certain errors in floating-point calculations. This is because the implementation of floating-point calculations on different platforms may be different, which will lead to inconsistent accuracy of calculation results. The code modified with the strictfp keyword can ensure that the same floating-point calculation method is used on all platforms, thereby ensuring the accuracy and consistency of the calculation results.

Here is an example using the strictfp modifier:

public strictfp class StrictfpExample {<!-- -->
    public strictfp double calculate(double x, double y) {<!-- -->
        return x * y;
    }
}

In the above sample code, the StrictfpExample class is declared as strictfp, and the calculate method is also declared as strictfp, which can ensure the The calculation results are consistent. For example, if it evaluates to 2.0 on one platform, it should also be 2.0 on another.

It should be noted that using the strictfp modifier will have a certain impact on performance, because it will limit the optimization of floating-point operations, so it needs to be used with caution.

In short, the strictfp modifier can be used to ensure the accuracy of floating-point calculations and to ensure the consistency of calculation results on different platforms. Its use can improve the portability and stability of the program, but it also needs to consider the performance impact.

1.2 transient: instantaneous

1.2.1 Preliminary introduction

transient: means instantaneous, temporary, short, fleeting;

  • Used to modify member variables;

The value of the member variable modified by transient, if the class implements the java.io.Serializable interface, then the member variable will not participate in serialization during the serialization process.

1.2.2 Further description

In Java, transient is a keyword used to modify member variables of a class.

When a variable is declared as transient, its value will not be saved when the object is serialized, that is, in the process of writing the object to a byte sequence, the member variable declared as transient will not be output to the character throttling.

When the object is deserialized, the member variables declared as transient will be restored to their default values, which is why the transient keyword is very useful in protecting sensitive information.

Here is an example using the transient modifier:

import java.io.Serializable;

public class Person implements Serializable{<!-- -->
    private String name;
    private transient int age;

    public Person(String name, int age) {<!-- -->
        this.name = name;
        this. age = age;
    }

    @Override
    public String toString() {<!-- -->
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}

In the above sample code, the Person class implements the Serializable interface, the name member variable is not declared as transient, and the age member variable is declared as transient. This means that the age member variable will not be declared when the object is serialized The value is serialized. During deserialization, the age member variable will be initialized to the default value 0.

It should be noted that the member variables declared as transient will not participate in the serialization process. If you need to implement serialization and deserialization logic by yourself, you need to manually use the object stream to read and write the values of these member variables.

To summarize here, the transient modifier can be used to protect sensitive information and ensure that they will not be written into the byte stream during serialization. Its use can improve the security and reliability of the program.

Second, in Java, keywords related to exception handling

2.1 try: try to execute, catch: try to catch exception object, finally: final block

2.1.1 Preliminary introduction

  • try: try to execute some code, if an exception occurs, an exception object will be thrown, let catch catch;

  • catch: Try to catch the exception object thrown in try. If the type matches, it can be caught, and the current method will not end; If all catches cannot be caught, the current method will end strong>.

  • finally: Regardless of whether there is an exception thrown in the try, whether the exception is caught by the catch, or whether there is a return statement in the try and catch, it will be executed.

Give the general form:

//Form 1:
try{<!-- -->
  statement block;
}catch(exception type 1 exception object name 1){<!-- -->
  Handle exception code block 1;
}catch(exception type 1 exception object name 1){<!-- -->
  Handle exception code block 1;
}
...
//Form 2:
try{<!-- -->
  statement block;
}catch(exception type 1 exception object name 1){<!-- -->
  Handle exception code block 1;
}catch(exception type 1 exception object name 1){<!-- -->
  Handle exception code block 1;
}
...
finally{<!-- -->
final statement block;
}
//Form 3:
try{<!-- -->
  statement block;
}finally{<!-- -->
  final statement block;
}

2.1.2 Further description

In Java, exception handling is an important programming technique that helps programs to be more robust in the face of errors and exceptional conditions. There are three keywords in Java for exception handling: try, catch, finally.

try: The try block is used to contain code blocks that want to catch exceptions. In the try block, if an exception occurs, the program will immediately jump to the catch block. Here is an example using a try block:

try {<!-- -->
    // some code that may throw an exception
} catch (ExceptionType e) {<!-- -->
    // handle the exception
}

In the sample code above, if an exception named ExceptionType occurs in the code in the try block, the program will jump to the catch block to continue execution.

catch: The catch block is used to catch the exception in the try block and handle it. In the catch block, you can specify the exception type to be caught, and you can also use multiple catch blocks to achieve exception polymorphism. Here is an example using a catch block:

try {<!-- -->
    // some code that may throw an exception
} catch (ExceptionType1 e) {<!-- -->
    // handle the ExceptionType1 exception
} catch (ExceptionType2 e) {<!-- -->
    // handle the ExceptionType2 exception
}

In the sample code above, if an exception named ExceptionType1 occurs in the code in the try block, the program will jump to the first catch block to continue execution. If the code in the try block has an exception named ExceptionType2, the program will jump to the second catch block to continue execution.

finally: The finally block is used to contain the code that will be executed regardless of whether an exception occurs after the code defined in the try block is executed. Here is an example using finally block:

try {<!-- -->
    // some code that may throw an exception
} catch (ExceptionType e) {<!-- -->
    // handle the exception
} finally {<!-- -->
    // some cleanup code that must always execute
}

In the above sample code, the code in the finally block will be executed regardless of whether an exception occurs in the code in the try block. In the finally block, you usually write necessary cleanup codes such as releasing resources.

Similarly, here is a summary: try, catch, finally are the three keywords used for exception handling in Java. Using these keywords can help programs to be more robust against errors and exceptions. When an exception may occur in the code, you can put the code in the try block, and then use the catch block to catch the exception and handle it. The code in the finally block will be executed whether or not an exception occurs.

2.2 throw: Throw

2.2.1 Preliminary introduction

For manually throwing exceptions:

throw exception object;
  • throw can be used to throw an exception object. If the exception it throws is not caught, it can replace the return statement to end the current method and bring the exception object back to the calling place.

  • User-defined exceptions can only be thrown manually using the throw statement.

2.2.2 Further description

In Java, throw is a keyword used to manually throw an exception. When the program executes to the throw statement, an exception object will be generated and thrown. If the exception is not handled in the program, the program will crash or terminate execution.

Here is an example using the throw keyword:

void someMethod(int num) throws Exception {<!-- -->
    if (num < 0) {<!-- -->
        // Throw an exception object
        throw new Exception("num cannot be negative");
    }
    // some code
}

In the above sample code, if the parameter num passed in is a negative number, an exception object named Exception will be thrown, and an exception information will be set in the exception object. When the someMethod() method is called, you can use the throws keyword to declare that the method may throw this exception, and then perform exception capture and processing at the place where the method is called .

It should be noted that when using the throw keyword, a defined exception type or its subtype must be thrown.

In short, the throw keyword can manually throw an exception object, which is used to actively trigger an exception in the program. When catching and handling exceptions, you can use the try-catch statement block. When an exception is thrown, the throws keyword can be used to declare that the exception may be thrown in the method. Throwing an exception is an important part of the Java exception handling mechanism, which can help the program to be more robust in the face of errors and abnormal conditions.

2.3 throws: throw exception list

2.3.1 Preliminary introduction

Used in the method signature to declare what types of exceptions the method will throw.

[modifier] return value type method name([parameter list]) throws exception type list{<!-- -->
 
}

Indicates that these exceptions are not handled in the current method and are handed over to the caller for processing.

2.3.2 Further description

In Java, throws is a keyword used in a method declaration to declare that the method may throw some kind of exception. Using the throws keyword can make the code that calls this method forcefully handle possible exceptions at compile time, increasing the robustness of the code.

Here is an example using the throws keyword:

public static void readFromFile(String filename) throws FileNotFoundException {<!-- -->
    InputStream is = new FileInputStream(filename);
    // some code that reads from the file.
}

In the sample code above, the readFromFile method declares that FileNotFoundException may be thrown. When this method is called, the compiler will force the caller to handle this type of exception. You can use the try-catch statement to catch and handle the exception, or you can continue to use the throws keyword to throw the exception. Let the higher level code handle it.

It should be noted that the exception declared with the throws keyword must inherit from the Exception class, or be a subclass of Exception. If RuntimeException is used in a declaration, no compile-time checking will be done.

Summary:

    1. The throws keyword can be used in the function declaration to declare the exception that the function may throw, so that the caller must handle the exception, or continue to use the throws keyword to throw the exception upward.
    1. Using the throws keyword can increase the robustness of your code, making your application more reliable in the face of errors and exceptions.

Keep updating!

Follow me and get more dry goods knowledge at the first time~~

Recommended popular columns:

  • Python & AI column: [Python from entry to artificial intelligence]
  • Front-end column: [Dream of front-end ~ beauty of code (H5 + CSS3 + JS.]
  • Literature Intensive Reading & amp; Project Column: [Small Project (Practical Combat + Case)]
  • C language/C + + column: [C language, C + + treasure book] (example + analysis)
  • Java series (Java basics/advanced/Spring series/Java software design patterns, etc.)
  • Problem Solving Column: 【Tools, Techniques, Solutions】
  • Join the Community to chase the light together: the light chaser ♂ community

Continue to create high-quality and good writing…?

Remember to click three times! ! !

Please pay attention! Ask for likes! Ask for a collection!