Home  >  Article  >  Java  >  Comparison of checked exceptions and unchecked exceptions

Comparison of checked exceptions and unchecked exceptions

零下一度
零下一度Original
2017-07-20 10:34:261689browse
For exceptions caused by programming errors, or exceptions that the program cannot be expected to catch (dereferencing a null pointer, array out of bounds, division by zero, etc.), in order to save developers from handling these exceptions, some exceptions are Exceptions are named unchecked (that is, those that inherit from RuntimeException) and do not need to be declared.
1. Checked exceptions: The JAVA compiler forces the use of try{}catch(){} blocks for processing. If not processed, it must be explicitly thrown using throws on the method containing the code that may cause the exception. If an exception occurs, the method that calls the method will catch and handle the exception. Otherwise, the program will not be compiled and a red cross will appear.
For example:

Here you must use try catch blocks to surround the code or throws to explicitly throw an exception. , otherwise the compilation will not pass.
2. Unchecked exceptions: Exceptions that can be passed by the JAVA compiler can be processed with try{}catch(){}. After processing, the program can continue to execute, or it can not be processed, by calling its method of processing. Of course, you can also leave it unprocessed. At the top level, if there are multiple threads, the thread will terminate, and if there is a single thread, the main program will terminate. That is to say, if the runtime exception is not processed, it will stop the program.
For example:
Although an exception is thrown here, it only prevents the program from continuing to run, and does not compile and report errors. There is no need to use the throws statement on the method. Explicitly throw an exception.

The above is the detailed content of Comparison of checked exceptions and unchecked exceptions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn