Resolve whether or not errors in Java should be caught

  • 2020-04-01 02:52:34
  • OfStack

When you write a Java program, you're often prompted to catch exceptions, and there are exceptions that you don't have to force to catch, which is an overblown topic. People like me who switch from other languages are a bit confused, so let me explain it again with my understanding.

The base class for exceptions is Exception, and the Exception subclass has RuntimeException and other exceptions. These other exceptions are called Checked exceptions, and runtimeexceptions are called Unchecked exceptions.

In plain English, Java prompts developers to catch known exceptions in order for programs to run stably. The compiler knows all types or methods that might throw exceptions, and when you use a certain type or method, the compiler prompts you to catch known exceptions. The Checked exceptions that the compiler is aware of are possible exceptions. For example, when you close a file stream and IOException is written in the close method that it might be thrown, the compiler tells you that you must catch the exception. The RuntimeException exception is not known at compile time and can only be determined at run time, such as when 3/0 (3 over 0) reports the ArithmeticException exception. Because this divisor can be changed at run time, it is not prompted for capture. These runtimeexceptions are Unchecked exceptions.

In short, Java is to make the program as stable as possible, you know the hint, do not know the helpless. That should make the explanation clearer.

Now I'm going to get down to business.

Some friends may have encountered this situation when debugging a program, the program clearly has an Exception, also catch (Exception e), but did not catch any information. There are two reasons: 1. The thread where the Exception is located is not the same thread as the thread you caught; 2. The program throws an Error instead of an Exception. An Error, like an Exception, inherits from Throwable and is a serious Error that should not be caught. When I saw this explanation, I was stupid enough not to understand why I should not catch errors. Because the Error situation will cause the program to be directly unable to run, so there is no sense in capturing. So here's my problem again, if I don't capture it, then the program has a problem and it exits, and I can't even see the log, what am I going to do? This assumption is not true, because if the Error did exist, you would have found the problem in the development environment and would not have been able to release it to the official environment.

Alas, having come a long way to do such a silly thing, so stop discussing whether the Error should have been caught!

My knowledge is still shallow, writing purpose is to get your advice. If the article helps you, that's great.


Related articles: