In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to understand Exception and Error in java". In daily operation, I believe many people have doubts about how to understand Exception and Error in java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to understand Exception and Error in java"! Next, please follow the editor to study!
The basic idea in Java is that poorly structured code can't run, and the ideal time to find errors is during compilation, because you don't have to run the program, you can find problems only by understanding the basic concepts of Java. But the compile time can not find all the problems, there are some NullPointerException and ClassNotFoundException can not be found at compile time, these exceptions are RuntimeException runtime exceptions, these exceptions are often found at run time.
We often have two kinds of problems when we write Java programs, one is java.lang.Exception, and the other is java.lang.Error, both of which are used to indicate that there is an abnormal situation.
Knowing that ExceptionException is under the java.lang package, it is a top-level interface that inherits from the Throwable class, and the Exception class and its subclasses are all the conditions for the composition of Throwable, which is a reasonable situation for the program.
Before you know Exception, it is necessary to know what Throwable is.
What is Throwable?
The Throwable class is the parent class of all errors (errors) and exceptions (exceptions) in the Java language. Only classes that inherit from Throwable or their subclasses can be thrown. Another way is that classes with @ throw annotations in Java can also be thrown.
In the Java specification, unchecked exceptions and checked exceptions are defined as follows:
"The unchecked exception classes are the run-time exception classes and the error classes.
"The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are Throwable and all its subclasses other than RuntimeException and its subclasses and Errorand its subclasses.
That is, except for RuntimeException and its subclasses, as well as error and its subclasses, all other exceptions are checkedException.
Then, according to this logical relationship, we can classify and analyze Throwable and its subcategories.
As you can see, Throwable is at the top level of exceptions and errors. We look at the Throwable class and find many of its methods and properties, and we only discuss a few of the more commonly used ones.
/ / return the details of throwing an exception public string getMessage (); public string getLocalizedMessage (); / / return a brief description of the occurrence of the exception public public String toString (); / / print the exception information to the standard output stream public void printStackTrace (); public void printStackTrace (PrintStream s); public void printStackTrace (PrintWriter s) / / record the current state of the stack frame public synchronized Throwable fillInStackTrace ()
In addition, because the parent class of Throwable is also Object, the common methods are getClass () and getName () methods that inherit its parent class.
Common Exception
Let's go back to the discussion of Exception. Now you know that the parent class of Exception is Throwable, and Exception has two kinds of exceptions, one is RuntimeException, and the other is CheckedException, both of which should be caught.
Here are some common exceptions in Java and their categories, and this interviewer may also ask you to name a few common exceptions and classify them.
RuntimeException
Sequence number exception name exception description
Sequence number exception name exception description 1ArrayIndexOutOfBoundsException array out of bounds exception 2NullPointerException null pointer exception 3IllegalArgumentException illegal parameter exception 4NegativeArraySizeException array length is negative 5IllegalStateException illegal state exception 6ClassCastException type conversion exception
UncheckedException
Sequence number exception name exception description 1NoSuchFieldException indicates that the class does not specify an exception thrown by the name 2NoSuchMethodException indicates that the class does not specify an exception thrown by the method 3IllegalAccessException does not allow access to an exception of a class the 4ClassNotFoundException class did not find an exception to throw
Java keywords related to Exception
So how do you handle these exceptions in Java? In Java, there are these keywords throws, throw, try, finally, catch. Let's discuss them respectively.
Throws and throw
In Java, an exception is an object that can be thrown by programmers or applications, and must be defined with the help of throws and throw statements.
Throws and throw usually appear in pairs, such as
Static void cacheException () throws Exception {throw new Exception ();}
The throw statement is used in the method body to indicate that an exception is thrown and is handled by the statement in the method body. The throws statement is used after the method declaration to indicate that an exception is thrown and is handled by the caller of the method.
Throws mainly declares that this method will throw this type of exception so that its caller knows to catch the exception. Throw is a concrete action that throws an exception, so it throws an exception instance.
Try 、 finally 、 catch
These three keywords are mainly combined in the following ways: try...catch, try...finally, try...catch...finally.
Try...catch represents the capture of an exception that may be thrown by a piece of code, as follows
Static void cacheException () throws Exception {try {System.out.println ("1");} catch (Exception e) {e.printStackTrace ();}}
Try...finally means that a piece of code will follow the code in finally no matter how it is executed.
Static void cacheException () throws Exception {for (int I = 0; I
< 5; i++) { System.out.println("enter: i=" + i); try { System.out.println("execute: i=" + i); continue; } finally { System.out.println("leave: i=" + i); } } } try...catch...finally 也是一样的,表示对异常捕获后,再走 finally 中的代码逻辑。 JDK1.7 使用 try...with...resources 优雅关闭资源 Java 类库中有许多资源需要通过 close 方法进行关闭。比如 InputStream、OutputStream,数据库连接对象 Connection,MyBatis 中的 SqlSession 会话等。作为开发人员经常会忽略掉资源的关闭方法,导致内存泄漏。 根据经验,try-finally语句是确保资源会被关闭的最佳方法,就算异常或者返回也一样。try-catch-finally 一般是这样来用的 static String firstLineOfFile(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); }finally { br.close(); } } 这样看起来代码还是比较整洁,但是当我们添加第二个需要关闭的资源的时候,就像下面这样 static void copy(String src,String dst) throws Exception{ InputStream is = new FileInputStream(src); try { OutputStream os = new FileOutputStream(dst); try { byte[] buf = new byte[100]; int n; while ((n = is.read()) >= 0) {os.write (buf,n,0);}} finally {os.close ();}} finally {is.close ();}}
In this way, it feels like this method has become bloated.
And there are many problems with this way of writing, even if try-finally can close the resource correctly, but it can not prevent exceptions from being thrown, because exceptions may occur in both try and finally blocks.
For example, if your hard drive is damaged while you are reading, you will not be able to read the file and close the resource, and two exceptions will be thrown. But in this case, the second exception erases the first exception. The record of the first exception can not be found in the exception stack, so what to do, do you catch the exception like this?
Static void tryThrowException (String path) throws Exception {BufferedReader br = new BufferedReader (new FileReader (path)); try {String s = br.readLine (); System.out.println ("s =" + s);} catch (Exception e) {e.printStackTrace ();} finally {try {br.close ();} catch (Exception e) {e.printStackTrace ();} finally {br.close () }}}
Although this method of writing can solve the problem of exception throwing, the nesting of various try-cath-finally can make the code very bloated.
All of these problems can be solved when try-with-resources statements are introduced into Java7. To use the try-with-resources statement, first implement the AutoCloseable interface, which contains a single returned close method. Many classes and interfaces in the Java class library and the tripartite class library now implement or extend the AutoCloseable interface. If you write a class that represents a resource that must be closed, then the class should implement the AutoCloseable interface.
Java introduces the try-with-resources declaration, which simplifies try-catch-finally to try-catch, which is actually a syntactic sugar that is converted into try-catch-finally statements at compile time.
Here is the first example of using try-with-resources
/ * * use try-with-resources to rewrite example one * @ param path * @ return * @ throws IOException * / static String firstLineOfFileAutoClose (String path) throws IOException {try (BufferedReader br = new BufferedReader (new FileReader (path) {return br.readLine ();}}
The second example of using try-with-resources to rewrite the program
Static void copyAutoClose (String src,String dst) throws IOException {try (InputStream in = new FileInputStream (src); OutputStream os = new FileOutputStream (dst)) {byte [] buf = new byte [1000]; int n; while ((n = in.read (buf)) > = 0) {os.write (buf,0,n);}
Using try-with-resources not only makes the code easier to understand, but also makes it easier to diagnose. Taking the firstLineOfFileAutoClose method as an example, if you call both the readLine () and close () methods to throw an exception, the latter exception is disabled to retain the first exception. (if the official account replies efficiently, you can get the Chinese pdf of the third edition of Effective Java)
Principles of exception handling
There are three principles that we should follow in our daily exception handling code:
Instead of catching exceptions like Exception, catch specific exceptions, such as InterruptedException, to facilitate troubleshooting and reduce the number of times you are scolded when others take over your code.
Don't swallow anomalies alive. This is something that should be paid special attention to in exception handling. If we do not throw the exception, or if it is not output to the Logger log, the program may end up in an uncontrollable manner later.
Do not use checkedException in functional programming.
What is Error?
Error is an error that the program cannot handle and indicates a serious problem in running the application. Most errors have nothing to do with the actions performed by the code writer and represent problems with the JVM (Java virtual machine) when the code is running. These errors are undetectable because they are outside the control and processing power of the application, and most of them are conditions that are not allowed when the program is running, such as OutOfMemoryError and StackOverflowError exceptions. Here we need to introduce the Java memory model JDK1.7.
It consists of two parts, which are composed of data areas shared by all threads and data areas isolated by threads. In the above Java memory model, only program counters are areas where OutOfMemoryError will not occur. Program counters control the branching, loop, jump, exception handling and thread recovery of computer instructions, and program counters are private to each thread.
"what is thread private: represents an area of memory that does not affect each other and is stored independently.
If the application is executing the Java method, this counter records the address of the virtual machine bytecode instruction; if the Native method is being executed, the counter value is Undefined.
In addition to program counters, other areas: method area (Method Area), virtual machine stack (VM Stack), local method stack (Native Method Stack), and heap (Heap) are all areas where OutOfMemoryError can occur.
Virtual machine stack: if the stack depth requested by the thread is greater than that allowed by the virtual machine stack, a StackOverflowError exception will occur; if the virtual machine dynamic extension cannot apply for enough memory, OutOfMemoryError will occur.
The local method stack is the same as the virtual machine stack
Heap: the Java heap can be physically discontiguous and logically contiguous, just like our disk space. If there is no memory in the heap to complete instance allocation, and the heap cannot be expanded, an OutOfMemoryError will be thrown.
Method area: when the method area cannot meet the memory allocation requirements, an OutOfMemoryError exception will be thrown.
A classic interview question
A very classic interview question, what's the difference between NoClassDefFoundError and ClassNotFoundException?
In the class loading process, JVM or ClassLoader can not find the corresponding class, may cause these two kinds of exception / error, because different ClassLoader will load the class from different places, sometimes caused by the wrong CLASSPATH classpath, sometimes caused by the missing jar package of a library. NoClassDefFoundError indicates that this class exists at compile time, but cannot be found at run time, and sometimes static initialization blocks can cause NoClassDefFoundError errors.
"ClassLoader is a classpath loader. In Java, there are three types of classpath loaders. One is the ClassLoader that comes with the virtual machine, which is divided into three types.
Start the classloader (Bootstrap), which loads $JAVAHOME/jre/lib/rt.jar
Extension class loader (Extension), which is responsible for loading $JAVAHOME/jre/lib/ext/*.jar
Application class loader (AppClassLoader), which loads all classes of the currently applied classpath
The second is a user-defined class loader
A subclass of Java.lang.ClassLoader, users can customize how the class is loaded.
On the other hand, ClassNotFoundException has nothing to do with compile time, and ClassNotFoundException appears when you try to load classes with reflection at run time.
In short, both ClassNotFoundException and NoClassDefFoundError are caused by the lack of classes in CLASSPATH, usually due to the lack of JAR files, but if JVM thinks that the application runtime can not find the corresponding reference, it will throw a NoClassDefFoundError error; when you show a load class such as Class.forName () call in the code but can not find the corresponding class, it will throw java.lang.ClassNotFoundException.
NoClassDefFoundError is an error caused by JVM, is unchecked, and is unchecked. Therefore, try-catch or finally statement blocks are not used; in addition, ClassNotFoundException is an exception being checked, so it needs to be surrounded by try-catch or try-finally statement blocks, otherwise it will result in compilation errors.
Calling methods such as Class.forName (), ClassLoader.findClass (), and ClassLoader.loadClass () may cause java.lang.ClassNotFoundException, as shown in the figure
NoClassDefFoundError is a link error that occurs during the link phase and is triggered when the parsing reference cannot find the corresponding class, while ClassNotFoundException is an exception that occurs at run time.
At this point, the study on "how to understand Exception and Error in java" 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.