On some differences between throwing exceptions and catching exceptions

  • 2021-09-11 20:16:25
  • OfStack

Small summary

Throw an exception:

Create an exception object, encapsulate the exception information, and pass the exception object to the caller via throw.

It is very irresponsible to throw exceptions without handling them, which can be called love rat.

However, some exceptions that are not recognized by jvm virtual machines can be thrown by actively throwing exceptions.

Example of throwing exceptions manually


public static void main(String[] args) throws Exception {
        int age = 0;
        age = -100;
        if(age<0)
        {
            Exception e = new Exception();// Create an exception object 
            throw e;// Throw an exception 
        }
        System.out.println(age);
    }

In common sense, the age of this example cannot be less than zero, so you should throw an exception manually.

Catch exceptions:

Catch exceptions and then handle them in a specified way

Differences between throw and throws:

1. Throw things differently: throw throws concrete exception objects, while throws throws abstract exception classes.

2. Use different places: throw1 is used in the method body as well as in the code block, and throws can only be used after the method declaration parentheses.

Exception Handling in Java: When to Throw Exceptions and When to Catch Exceptions?

When looking at the source code of hadoop, think about the system you are doing recently, and find that many exception handling methods are wrong, or according to the traditional exception handling methods (i.e., using return values to identify abnormal situations in programs). While the declarations of many methods in hadoop have exceptions thrown, the declarations of many methods in my system have not thrown exceptions. Only the exception was judged and an error prompt was output, but no exception was thrown.

readFields () method of Block class under org. apache. hadoop. hdfs package:


public void readFields(DataInput in) throws IOException {
    this.blockId = in.readLong();
    this.numBytes = in.readLong();
    this.generationStamp = in.readLong();
    if (numBytes < 0) {
      throw new IOException("Unexpected block size: " + numBytes);// Throw an exception, if it is, it will not be thrown, but only System.out.println Error prompt, 
    }

1. If there is an throws exception in the method declaration name, then no exception can be thrown in the method body.

Because you can include an exception description in the method declaration, but you don't actually throw it! The advantage of this is that you take a place for exceptions and you can throw them later without modifying existing code. This ability is important when defining abstract base classes and interfaces so that derived or interface implementation classes can throw these pre-declared exceptions.

2. Why do some method declarations have no throws in them, but an exception is thrown in the method body?

Exceptions inherited from RuntimeException can be thrown without exception description of throws! For Runtime exceptions (also known as unchecked exceptions unchecked exception), the compiler does not need an exception description. Exceptions of type RuntimeException (and its subclasses) can only be ignored in code, and the handling of other types of exceptions is compiler-enforced. The reason is that RuntimeException represents programming errors.

3. Runtime exceptions will be automatically thrown by Java virtual machine!

1. Fundamentals of Exception Handling

1.1 System. out. println is costly. Calling System. out. println reduces system throughput.

1.2 Do not use the exceptional printStackTrace () method in a production environment. printStackTrace prints the call stack to the console by default, and accessing the console in a production environment is not realistic.

2. Basic principles of exception handling

2.1 If you cannot handle an exception, do not catch it.

2.2 If you want to catch it, you should catch it near the source of the exception.

2.3 Don't engulf the anomalies you catch.

* (Is the exception caught, but does nothing)

2.4 Unless you want to throw an exception again, put it log.

2.5 Do not print statck trace when an exception is repackaged and then thrown again.

2.6 Don't throw java. lang. Exception every time you need to throw an exception with a custom exception class. Method callers can use throws to know which exceptions need to be handled--so it is self-describing.

2.7 If you write business logic, the system should throw unchecked exceptions (unchecked exception) for errors that cannot be fixed by end users; If you write a third-party package for other developers, use exceptions that need to be checked for irreparable errors (checked exception).

2.8 Never fail to declare exceptions that need to be checked because writing throws statements will make you uncomfortable to use.

2.9 Application-level errors or irreparable system exceptions are thrown as unchecked exceptions (unchecked exception).

* (Note that it is an error, which means that it cannot be repaired, such as a configuration file error)

2.10 Organize your methods according to the granularity of exceptions


Related articles: