In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the relevant knowledge of "what are the ten key knowledge points of Java exception". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "what are the ten key knowledge points of Java exception" can help you solve the problem.
one。 What is the exception?
An exception is a problem that prevents the current method or scope from continuing execution. For example, the file you read does not exist, the array is out of bounds, when dividing, the divisor is 0, and so on will cause exceptions.
An exception that cannot be found in the file:
Public class TestException {public static void main (String [] args) throws IOException {InputStream is = new FileInputStream ("jaywei.txt"); int b; while ((b = is.read ())! =-1) {}
Running result:
Exception in thread "main" java.io.FileNotFoundException: jaywei.txt (the system cannot find the specified file.) At java.io.FileInputStream.open0 (Native Method) at java.io.FileInputStream.open (FileInputStream.java:195) at java.io.FileInputStream. (FileInputStream.java:138) at java.io.FileInputStream. (FileInputStream.java:93) at exception.TestException.main (TestException.java:10) II. The hierarchy of exceptions
Once upon a time, there was an old man whose name was Throwable. He had two sons. The eldest son was Error and the second son was Exception.
Error
Indicates compile-time or system errors, such as virtual machine-related errors, OutOfMemoryError, etc., that error cannot handle.
Exception
Code exception, the base type that Java programmers care about is usually Exception. It can be handled by the program itself, which is the difference between it and Error.
It can be divided into RuntimeException (runtime exceptions) and CheckedException (detectable exceptions).
Common RuntimeException exceptions:
-NullPointerException null pointer exception-throw this exception when an exception occurs in ArithmeticException-IndexOutOfBoundsException array index out of bounds exception-ClassNotFoundException cannot find class exception-IllegalArgumentException (illegal parameter exception)
Common Checked Exception exceptions:
-IOException (possible exceptions when manipulating input and output streams)-ClassCastException (type conversion exception class)
Checked Exception is the exception that the compiler requires you to handle.
By contrast, Unchecked Exceptions, which refers to exceptions that the compiler does not require mandatory handling, includes Error and RuntimeException and their subclasses.
Third, exception handling
When an exception occurs, an exception object is created on the heap. The current execution path is terminated and a reference to the exception object pops up from the current environment. At this time, the exception handler recovers the program from the error state and keeps the program running.
Exception handling mainly includes throwing exception, catching exception and declaring exception. As shown in the figure:
Catch exception
Try {/ / Program Code} catch (Exception e) {/ / Catch Block} finaly {/ / the code block that will be executed anyway
We can use try...catch... Catch the exception code, and then perform the final actions through finaly, such as closing the stream.
Declaration throws an exception
Except for try...catch.... Catch an exception, and we can also throw an exception through the throws declaration.
When you define a method, you can declare it with the throws keyword. The use of the throws keyword indicates that the method does not handle exceptions, but leaves them to its callers. Do you think TA is irresponsible?
Haha, take a look at demo.
/ / this method declares an IO exception through throws. Private void readFile () throws IOException {InputStream is = new FileInputStream ("jaywei.txt"); int b; while ((b = is.read ())! =-1) {}}
Declare that any exception thrown from the method must use the throws clause.
Throw an exception
The function of the throw keyword is to throw an exception of type Throwable, which usually occurs in the function body. In exception handling, the try statement catches an exception object, which can also be thrown by itself.
For example, throw an exception object of the RuntimeException class:
Throw new RuntimeException (e)
Any Java code can throw an exception through the throw statement of Java.
Pay attention
Non-checked exceptions (Error, RuntimeException, or their subclasses) cannot use the throws keyword to declare the exception to be thrown.
If a method has a compile-time exception, it needs to be handled by try-catch/ throws, otherwise it will result in a compilation error.
IV. Try-catch-finally-return execution order
Try-catch-finally-return execution description
If no exception occurs, the catch section is not executed.
Finally executes whether there is an exception or not.
Even when there is return in try and catch, finally still executes
Finally is executed after the expression after return has been evaluated. (at this time, the value to be returned is not returned, but the value to be returned is saved first. If there is no return in finally, the returned value will remain unchanged regardless of the code in finally.) in this case, the return value of the function is determined before the execution of finally.)
Don't return in the finally part, otherwise, you won't be able to go back to try or catch's return.
Look at an example.
Public static void main (String [] args) throws IOException {System.out.println ("result:" + test ());} private static int test () {int temp = 1; try {System.out.println ("start execute try,temp is:" + temp); return + + temp;} catch (Exception e) {System.out.println ("start execute catch temp is:" + temp) Return + + temp;} finally {System.out.println ("start execute finally,temp is:" + temp); + + temp;}
Running result:
Start execute try,temp is:1 start execute finally,temp is:2 result:2
Analysis.
First execute the try section, output the log, execute the + + temp expression, temp becomes 2, and this value is saved.
The catch code block is skipped because no exception has occurred.
Execute finally code blocks, output logs, and execute + + temp expressions.
Returns the value saved in the try section 2. 0.
5. Several important methods of Java exception class.
Let's first take a look at all the methods of exception classes, as shown below:
GetMessage
Returns the detail message string of this throwable.
GetMessage returns the detailMessage property of Throwable, and detailMessage represents a detailed message description of the exception that occurred.
For example, when a FileNotFoundException exception occurs, the detailMessage contains the name of the file that cannot be found.
GetLocalizedMessage
Creates a localized description of this throwable.Subclasses may override this method in order to produce alocale-specific message. For subclasses that do not override thismethod, the default implementation returns the same result as getMessage ()
Localized description of the throwable. Subclasses can override this method to generate locale-specific messages. For subclasses that do not override this method, the default implementation returns the same result getMessage ().
GetCause
Returns thecause of this throwable or null if thecause is nonexistent or unknown.
Returns the cause of the event that can be thrown, or null if the reason does not exist or is unknown.
PrintStackTrace
Prints this throwable and its backtrace to thestandard error stream. The first line of output contains the result of the toString () method for this object.Remaining lines represent data previously recorded by the method fillInStackTrace ().
This method prints stack trace information to the standard error stream.
The first line of the output contains the results of the object's toString () method. The remaining lines represent the data previously recorded by the method fillInStackTrace (). Examples are as follows:
Java.lang.NullPointerException at MyClass.mash (MyClass.java:9) at MyClass.crunch (MyClass.java:6) at MyClass.main (MyClass.java:3) VI. Custom exception
A custom exception usually defines a subclass that inherits from the Exception class.
So, why do you need custom exceptions?
The exception system provided by Java cannot foresee all errors.
In business development, using custom exceptions can make the project code more standardized and easy to manage.
The following is a simple demo of our custom exception class
Public class BizException extends Exception {/ / error message private String message; / / error code private String errorCode; public BizException () {} public BizException (String message, String errorCode) {this.message = message; this.errorCode = errorCode;} @ Override public String getMessage () {return message } public void setMessage (String message) {this.message = message;} public String getErrorCode () {return errorCode;} public void setErrorCode (String errorCode) {this.errorCode = errorCode;}}
Run a main to test it.
Public class TestBizException {public static void testBizException () throws BizException {System.out.println ("throwing BizException from testBizException ()"); throw new BizException ("100th", "I was wrong");} public static void main (String [] args) {try {testBizException ();} catch (BizException e) {System.out.println ("self-defined exception") E.printStackTrace ();}
Running result:
Exception.BizException: 100 throwing BizException from testBizException () self-defined exception at exception.TestBizException.testBizException (TestBizException.java:7) at exception.TestBizException.main (TestBizException.java:12) 7. Java7 new try-with-resources statement
Try-with-resources, a new feature provided by Java7, is used for automatic resource management.
Resources are objects that must be closed after the program runs out.
Try-with-resources guarantees that each declared resource will be closed at the end of the statement
What kind of objects can be used as resources? Any object that implements either the java.lang.AutoCloseable interface or the java.io.Closeable interface is OK.
Before the emergence of try-with-resources
Try {/ / open resources like File, Database connection, Sockets etc} catch (FileNotFoundException e) {/ / Exception handling like FileNotFoundException, IOException etc} finally {/ / close resources}
After the emergence of Java7,try-with-resources, use resources to implement
Try (/ / open resources here) {/ / use resources} catch (FileNotFoundException e) {/ / exception handling} / / resources are closed as soon as try-catch block is executed.
Java7 uses resource demo
Public class Java7TryResourceTest {public static void main (String [] args) {try (BufferedReader br = new BufferedReader (new FileReader ("C:/jaywei.txt") {System.out.println (br.readLine ());} catch (IOException e) {e.printStackTrace ();}
Benefits of using try-with-resources
The code is more elegant and has fewer lines.
Automatic resource management, do not have to worry about memory leaks.
8. Abnormal chain
We often want to throw an exception after catching another exception, and we want to save the information about the original exception, which is called an exception chain.
Throw throws a new exception information, which will result in the loss of the original exception information. Before JDk1.4, programmers had to write their own code to save the original exception information. All Throwable subclasses can now accept a cause (exception cause) object as a parameter in the constructor.
This cause is used to represent the original exception, so that even if the new exception is created and thrown at the current location, the original exception can be traced to the original location of the exception through this exception chain.
The mode of use is as follows:
Public class TestChainException {public void readFile () throws MyException {try {InputStream is = new FileInputStream ("jay.txt"); Scanner in = new Scanner (is); while (in.hasNext ()) {System.out.println (in.next ()) }} catch (FileNotFoundException e) {/ / e save exception information throw new MyException ("where is the file", e);}} public void invokeReadFile () throws MyException {try {readFile () } catch (MyException e) {/ / e saves exception information throw new MyException ("file not found", e);}} public static void main (String [] args) {TestChainException t = new TestChainException (); try {t.invokeReadFile ();} catch (MyException e) {e.printStackTrace () MyException constructor public MyException (String message, Throwable cause) {super (message, cause);}
Running result:
We can see that some of the exception messages have been saved. If cause (that is, e of FileNotFoundException) is removed, take a look at the running result:
It can be found that without Throwable cause, the original abnormal information is missing.
IX. Abnormal matching
When an exception is thrown, the exception handling system finds the "nearest" handler in the order in which the code is written. Once a matching handler is found, it assumes that the exception will be handled and then stops looking.
When looking for it, it is not required that the exception thrown match exactly the exception of the handler. Objects of derived classes can also be equipped with handlers of their base classes
Look at demo.
Package exceptions; / /: exceptions/Human.java / / Catching exception hierarchies. Class Annoyance extends Exception {} class Sneeze extends Annoyance {} public class Human {public static void main (String [] args) {/ / Catch the exact type: try {throw new Sneeze ();} catch (Sneeze s) {System.out.println ("Caught Sneeze");} catch (Annoyance a) {System.out.println ("Caught Annoyance");} / Catch the base type: try {throw new Sneeze () } catch (Annoyance a) {System.out.println ("Caught Annoyance");}
Running result:
Catch (Annoyance a) catches Annoyance and all exceptions derived from it. By catching the exceptions of the base class, you can match the exceptions of all derived classes
Try {throw new Sneeze ();} catch (Annoyance a) {} catch (Sneeze s) {/ / the compiler will report an error because the exception has been handled by the previous catch clause. Java common exceptions
NullPointerException
Null pointer exception, the most common exception class. In short, this exception occurs when an uninitialized object or an object that does not exist is called.
ArithmeticException
Arithmetic exception class, such an exception occurs when there is an operation such as a divisor of 0 in the program.
ClassCastException
Type cast exception, which is the run-time exception that JVM throws when it detects a conversion incompatibility between two types.
ArrayIndexOutOfBoundsException
Array subscript out of bounds exception, when dealing with the array, you need to pay attention to this exception.
FileNotFoundException
No exception was found in the file, which is usually a file to read or write, but could not be found, resulting in the exception.
SQLException
Operation database exception, which is Checked Exception (check for exceptions)
IOException
IO exception, which is usually closely related to reading and writing files, is also Checked Exception (check for exceptions). Usually read and write files, remember that the IO stream is closed!
NoSuchMethodException
Method did not find an exception
NumberFormatException
Convert a string to a numeric exception
This is the end of the content about "what are the ten key knowledge points of Java exception". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.