In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "java checked and unchecked exception case analysis". In daily operation, I believe that many people have doubts about java checked and unchecked exception case analysis. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "java checked and unchecked exception case analysis". Next, please follow the editor to study!
There are two types of Java exceptions, checked exception and unchecked exception, and the other is called exception and error.
In a nutshell, checked is recoverable during execution, while unchecked exceptions are unhandled errors.
Checked exception:
Indicates invalid and is not predictable in the program. For example, invalid user input, file does not exist, network or database link error. These are all external reasons and are not controllable within the program.
Must be handled explicitly in the code. For example, try-catch block handling, or add a throws description to the method and throw the exception one level above the call stack.
Inherited from java.lang.Exception (except java.lang.RuntimeException).
Unchecked exception:
Indicates an error, a logic error of the program. Are subclasses of RuntimeException, such as IllegalArgumentException, NullPointerException, and IllegalStateException.
There is no need to explicitly catch unchecked exceptions in your code for handling.
Inherits from java.lang.RuntimeException (while java.lang.RuntimeException inherits from java.lang.Exception).
The checked exception in Java needs to be caught or thrown explicitly through try-catch in the code. If you do not need to handle this exception, you can simply throw the exception again. This exception has some shortcomings. Many people are used to writing an empty catch block directly in the code, which not only makes the code redundant and "ugly", but also brings trouble to debugging and increases the difficulty of code maintenance. So some people say that checked makes the code verbose, and empty catch blocks don't make sense, so checked exceptions should be removed from the Java standard. For example, there is no concept of checked exceptions in C #, and explicit exceptions are not forced to be caught in C #.
The reason why Java exceptions can be divided into these two types is due to the following considerations:
Checked exceptions can help developers be aware of which lines are likely to have exceptions, because Java's API has indicated which methods might throw exceptions when called. If you do not process the compilation, you can not pass, to some extent, this practice can avoid some errors in the program.
Two simple examples
1.checked exception
Import java.io.BufferedReader;import java.io.File;import java.io.FileReader;public class Main {public static void main (String [] args) {File f = new File ("C:\ test.txt"); FileReader r = new FileReader (f); / / ABufferedReader br = new BufferedReader (r); br.readLine (); / / Bbr.close (); / / C}}
This code cannot be compiled because lines B and C throw IOException, which must be placed in a try-catch block, or throws IOException must be added to the main method to compile.
2. Unchecked exception
Public class Main {public static void main (String [] args) {int a = 0nint b = 100poliint c = bAccord a;}}
Can be compiled, but execution will report an error
Exception in thread "main" java.lang.ArithmeticException: / by zeroat Main.main (Main.java:13)
ArithmeticException is a unchecked exception.
Custom exception
1. Checked exception
Custom exception class InvalidUrlException
Public class InvalidUrlException extends Exception {public InvalidUrlException (String s) {super (s);}} public class Main {public static void getRemoteData (String url) throws InvalidUrlException {if (isValidUrl (url)) {/ / get remote data} elsethrow new InvalidUrlException ("Invalid URL:" + url);} public static boolean isValidUrl (String url) {.... / / verify whether URL is valid} public static void main (String [] args) {getRemoteData (args [0]);}}
If you call getRemoteData in the main method, there are two ways, one is try-catch, and the other is to add throws InvalidUrlException to main directly.
2. Unchecked exception
If you change InvalidUrlException to extends RuntimeException
Public class InvalidUrlException extends Exception {public InvalidUrlException (String) {super (s);}}
Then main does not need to add throws or try-catch.
Choose checked or unchecked exception?
Some Java books recommend using all recoverable exceptions in checked exception handlers and using unchecked exceptions as unrecoverable errors. But in fact, most of the Java exceptions inherited from RuntimeException can also be recovered in the program, such as NullPointerException, IllegalArgumentExceptions, dividing 0 exceptions, and so on. Only some special cases can break the execution of the program, such as reading the configuration file at startup, and if the configuration file does not exist or there is a serious error, the program has to exit.
Here are some arguments for and against checked exceptions:
The compiler forces unchecked exceptions to be caught or thrown so that developers always remember to handle the exception.
A method that throws a checked exception must declare that throws,throws has become part of the method or interface, making it inconvenient for subsequent versions to add or modify method exceptions.
Unchecked exceptions do not need to be handled explicitly, but make exception handling difficult.
To call a method with an checked exception, you must handle the method's exception, which confuses the upper-level caller code.
It's up to you to choose checked or unchecked. It's hard to say which is right or wrong. Among the more popular languages at present, Java seems to be the only language that supports checked exceptions, and other languages have only unchecked exceptions.
At this point, the study on "java checked and unchecked exception case analysis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.