The following article summarizes the ten key knowledge points of Java exceptions, which are useful in interviews or work. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
1. What is exception
Exception refers to blocking the current method or scope Problem with continuation. For example, the file you are reading does not exist, the array is out of bounds, and when performing division, the divisor is 0, etc., which will cause exceptions.
[Recommended learning: java video tutorial]
A file cannot be found exception:
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 (系統(tǒng)找不到指定的文件。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at exception.TestException.main(TestException.java:10)
2. Abnormal hierarchy
Once upon a time, there were An old man, his name is Throwable, he gave birth to two sons, the eldest son is called Error, and the second son is called Exception.
Error
indicates compilation or system errors, such as virtual machine-related errors, OutOfMemoryError, etc. The error cannot be handled.
Exception
Code exception, the base type that Java programmers care about is usually Exception. It can be processed by the program itself, which is the difference between it and Error.
It can be divided into RuntimeException (runtime exception) and CheckedException (checkable exception).
Common RuntimeException:
- NullPointerException 空指針異常 - ArithmeticException 出現(xiàn)異常的運(yùn)算條件時(shí),拋出此異常 - IndexOutOfBoundsException 數(shù)組索引越界異常 - ClassNotFoundException 找不到類異常 - IllegalArgumentException(非法參數(shù)異常)
Common Checked Exception:
- IOException (操作輸入流和輸出流時(shí)可能出現(xiàn)的異常) - ClassCastException(類型轉(zhuǎn)換異常類)
● Checked Exception is the compiler requirement You must handle exceptions.
● On the contrary, Unchecked Exceptions, which refers to exceptions that the compiler does not require forced handling, includes Error and RuntimeException and their subclasses.
3. Exception handling
When an exception occurs, an exception object will be created on the heap. The current execution path is terminated and a reference to the exception object is popped from the current environment. At this time, the Exception handling program recovers the program from the error state and allows the program to continue running.
Exception handling mainly includes throwing exceptions, catching exceptions, and declaring exceptions. As shown in the figure:
Catch exception
try{ // 程序代碼 }catch(Exception e){ //Catch 塊 }finaly{ //無論如何,都會(huì)執(zhí)行的代碼塊 }
We can capture the exception code through try...catch...
, and then pass finaly
Perform the final operations, such as closing the stream and other operations.
Declaration of throwing exceptions
In addition to try...catch...
catching exceptions, we can also declare exceptions through throws.
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 caller. Do you think TA is irresponsible?
Haha, take a look at the demo
//該方法通過throws聲明了IO異常。 private void readFile() throws IOException { InputStream is = new FileInputStream("jaywei.txt"); int b; while ((b = is.read()) != -1) { } }
Any exception declared to be thrown from a method must use the throws clause.
Throw exception
The function of the throw keyword is to throw an exception of type Throwable
, which generally appears in the function body. In exception handling, the try statement captures an exception object. In fact, this exception object 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 Java throw statement.
Notes
● Unchecked exceptions (Error, RuntimeException or their subclasses) cannot use the throws keyword to declare the exception to be thrown.
●If a method encounters a compile-time exception, it needs to be handled by try-catch/throws, otherwise it will cause a compilation error.
4. Try-catch-finally-return execution sequence
try-catch-finally-return execution description
●If no exception occurs, the catch part will not be executed.
●No matter whether an exception occurs or not, finally will be executed.
● Even if there is a return in try and catch, finally will still be executed
●Finally is executed after the expression following the return has been evaluated. (At this time, the calculated value is not returned, but the value to be returned is saved first. If there is no return in finally, the returned value will not change regardless of the code in finally, and will still be the one saved before. value), in this case the function return value is determined before finally execution)
● Don’t return in the finally part, otherwise, you won’t be able to go back to the try or catch 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 results:
start execute try,temp is:1 start execute finally,temp is:2 result:2
Analysis
●●Execute the try part first, output the log, and execute the temp
expression, temp becomes 2, and this value is saved.
● 因?yàn)闆]有發(fā)生異常,所以catch代碼塊跳過。
● 執(zhí)行finally代碼塊,輸出日志,執(zhí)行 ++temp
表達(dá)式.
● 返回try部分保存的值2.
五、Java異常類的幾個(gè)重要方法
先來喵一眼異常類的所有方法,如下圖:
getMessage
Returns the detail message string of this throwable.
getMessage會(huì)返回Throwable的 detailMessage
屬性,而 detailMessage
就表示發(fā)生異常的詳細(xì)消息描述。
舉個(gè)例子, FileNotFoundException
異常發(fā)生時(shí),這個(gè) detailMessage
就包含這個(gè)找不到文件的名字。
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()
throwable的本地化描述。子類可以重寫此方法,以生成特定于語言環(huán)境的消息。對于不覆蓋此方法的子類,默認(rèn)實(shí)現(xiàn)返回與相同的結(jié)果 getMessage()。
getCause
Returns the cause of this throwable or null if thecause is nonexistent or unknown.
返回此可拋出事件的原因,或者,如果原因不存在或未知,返回null。
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().
該方法將堆棧跟蹤信息打印到標(biāo)準(zhǔn)錯(cuò)誤流。
輸出的第一行,包含此對象toString()方法的結(jié)果。剩余的行表示,先前被方法fillInStackTrace()記錄的數(shù)據(jù)。如下例子:
java.lang.NullPointerException at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3)
六、自定義異常
自定義異常通常是定義一個(gè)繼承自 Exception 類的子類。
那么,為什么需要自定義異常?
● Java提供的異常體系不可能預(yù)見所有的錯(cuò)誤。
● 業(yè)務(wù)開發(fā)中,使用自定義異常,可以讓項(xiàng)目代碼更加規(guī)范,也便于管理。
下面是我司自定義異常類的一個(gè)簡單demo
public class BizException extends Exception { //錯(cuò)誤信息 private String message; //錯(cuò)誤碼 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; } }
跑個(gè)main方測試一下
public class TestBizException { public static void testBizException() throws BizException { System.out.println("throwing BizException from testBizException()"); throw new BizException("100","哥,我錯(cuò)了"); } public static void main(String[] args) { try { testBizException(); } catch (BizException e) { System.out.println("自己定義的異常"); e.printStackTrace(); } } }
運(yùn)行結(jié)果:
exception.BizException: 100 throwing BizException from testBizException() 自己定義的異常 at exception.TestBizException.testBizException(TestBizException.java:7) at exception.TestBizException.main(TestBizException.java:12)
七、Java7 新的 try-with-resources語句
try-with-resources,是Java7提供的一個(gè)新功能,它用于自動(dòng)資源管理。
● 資源是指在程序用完了之后必須要關(guān)閉的對象。
● try-with-resources保證了每個(gè)聲明了的資源在語句結(jié)束的時(shí)候會(huì)被關(guān)閉
● 什么樣的對象才能當(dāng)做資源使用呢?只要實(shí)現(xiàn)了java.lang.AutoCloseable接口或者java.io.Closeable接口的對象,都OK。
在 try-with-resources
出現(xiàn)之前
try{ //open resources like File, Database connection, Sockets etc } catch (FileNotFoundException e) { // Exception handling like FileNotFoundException, IOException etc }finally{ // close resources }
Java7, try-with-resources
出現(xiàn)之后,使用資源實(shí)現(xiàn)
try(// open resources here){ // use resources } catch (FileNotFoundException e) { // exception handling } // resources are closed as soon as try-catch block is executed.
Java7使用資源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(); } } }
使用了 try-with-resources
的好處
● 代碼更加優(yōu)雅,行數(shù)更少。
● 資源自動(dòng)管理,不用擔(dān)心內(nèi)存泄漏問題。
八、異常鏈
我們常常會(huì)想要在捕獲一個(gè)異常后拋出另一個(gè)異常,并且希望把原始異常的信息保存下來,這被稱為異常鏈。
throw 拋出的是一個(gè)新的異常信息,這樣會(huì)導(dǎo)致原有的異常信息丟失。在JDk1.4以前,程序員必須自己編寫代碼來保存原始異常信息?,F(xiàn)在所有 Throwable
子類在構(gòu)造器中都可以接受一個(gè) cause(異常因由)
對象作為參數(shù)。
這個(gè) cause
就用來表示原始異常,這樣通過把原始異常傳遞給新的異常,使得即使當(dāng)前位置創(chuàng)建并拋出了新的異常,也能通過這個(gè)異常鏈追蹤到異常最初發(fā)生的位置。
使用方式如下:
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 保存異常信息 throw new MyException("文件在哪里呢", e); } } public void invokeReadFile() throws MyException{ try { readFile(); } catch (MyException e) { //e 保存異常信息 throw new MyException("文件找不到", e); } } public static void main(String[] args) { TestChainException t = new TestChainException(); try { t.invokeReadFile(); } catch (MyException e) { e.printStackTrace(); } } } //MyException 構(gòu)造器 public MyException(String message, Throwable cause) { super(message, cause); }
運(yùn)行結(jié)果:
我們可以看到異常信息有保存下來的,如果把cause(也就是FileNotFoundException 的e)去掉呢,看一下運(yùn)行結(jié)果:
可以發(fā)現(xiàn),少了 Throwablecause
,原始異常信息不翼而飛了。
九、異常匹配
拋出異常的時(shí)候,異常處理系統(tǒng)會(huì)按照代碼的書寫順序找出"最近"的處理程序。找到匹配的處理程序之后,它就認(rèn)為異常將得到處理,然后就不再繼續(xù)查找。
查找的時(shí)候并不要求拋出的異常同處理程序的異常完全匹配。派生類的對象也可以配備其基類的處理程序
看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"); } } }
運(yùn)行結(jié)果:
catch(Annoyance a)會(huì)捕獲Annoyance以及所有從它派生的異常。捕獲基類的異常,就可以匹配所有派生類的異常
try { throw new Sneeze(); } catch(Annoyance a) { } catch(Sneeze s) { //這句編譯器會(huì)報(bào)錯(cuò),因?yàn)楫惓R延汕懊鎐atch子句處理 }
十、Java常見異常
NullPointerException
空指針異常,最常見的一個(gè)異常類。簡言之,調(diào)用了未經(jīng)初始化的對象或者是不存在的對象,就會(huì)產(chǎn)生該異常。
ArithmeticException
算術(shù)異常類,程序中出現(xiàn)了除數(shù)為0這樣的運(yùn)算,就會(huì)出現(xiàn)這樣的異常。
ClassCastException
類型強(qiáng)制轉(zhuǎn)換異常,它是JVM在檢測到兩個(gè)類型間轉(zhuǎn)換不兼容時(shí)引發(fā)的運(yùn)行時(shí)異常。
ArrayIndexOutOfBoundsException
數(shù)組下標(biāo)越界異常,跟數(shù)組打交道時(shí),需要注意一下這個(gè)異常。
FileNotFoundException
文件未找到異常,一般是要讀或者寫的文件,找不到,導(dǎo)致該異常。
SQLException
操作數(shù)據(jù)庫異常,它是Checked Exception(檢查異常);
IOException
IO異常,一般跟讀寫文件息息相關(guān),它也是Checked Exception(檢查異常)。平時(shí)讀寫文件,記得IO流關(guān)閉!
NoSuchMethodException
方法未找到異常
NumberFormatException
字符串轉(zhuǎn)換為數(shù)字異常
總結(jié)
這個(gè)總結(jié)獨(dú)辟蹊徑,以幾道經(jīng)典異常面試題結(jié)束吧,以幫助大家復(fù)習(xí)一下,嘻嘻。
● java 異常有哪幾種,特點(diǎn)是什么?(知識(shí)點(diǎn)二可答)
● 什么是Java中的異常?(知識(shí)點(diǎn)一可答)
● error和exception有什么區(qū)別?(知識(shí)點(diǎn)二可答)
● 什么是異常鏈?(知識(shí)點(diǎn)八可答)
● try-catch-finally-return執(zhí)行順序(知識(shí)點(diǎn)四可答)
● 列出常見的幾種RunException (知識(shí)點(diǎn)二可答)
● Java異常類的重要方法是什么?(知識(shí)點(diǎn)五可答)
● error和exception的區(qū)別,CheckedException,RuntimeException的區(qū)別。(知識(shí)點(diǎn)二可答)
● 請列出5個(gè)運(yùn)行時(shí)異常。(知識(shí)點(diǎn)二可答)
● Java 7 新的 try-with-resources 語句(知識(shí)點(diǎn)七可答)
● 怎么自定義異常?(知識(shí)點(diǎn)六可答)
● 說一下常見異常以及產(chǎn)生原因(知識(shí)點(diǎn)十可答)
● 談?wù)劗惓Fヅ洌ㄖR(shí)點(diǎn)九可答)
● 談?wù)劗惓L幚恚ㄖR(shí)點(diǎn)三可答)
本文來自?java入門?欄目,歡迎學(xué)習(xí)!
The above is the detailed content of 10 key knowledge points about Java exceptions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ReentrantLock provides more flexible thread control in Java than synchronized. 1. It supports non-blocking acquisition locks (tryLock()), lock acquisition with timeout (tryLock(longtimeout, TimeUnitunit)) and interruptible wait locks; 2. Allows fair locks to avoid thread hunger; 3. Supports multiple condition variables to achieve a more refined wait/notification mechanism; 4. Need to manually release the lock, unlock() must be called in finally blocks to avoid resource leakage; 5. It is suitable for scenarios that require advanced synchronization control, such as custom synchronization tools or complex concurrent structures, but synchro is still recommended for simple mutual exclusion requirements.
