Home >Java >Javagetting Started >10 key knowledge points about Java exceptions
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 (系统找不到指定的文件。) 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.
indicates compilation or system errors, such as virtual machine-related errors, OutOfMemoryError, etc. The error cannot be handled.
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 出现异常的运算条件时,抛出此异常 - IndexOutOfBoundsException 数组索引越界异常 - ClassNotFoundException 找不到类异常 - IllegalArgumentException(非法参数异常)
Common Checked Exception:
- IOException (操作输入流和输出流时可能出现的异常) - ClassCastException(类型转换异常类)
● 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:
try{ // 程序代码 }catch(Exception e){ //Catch 块 }finaly{ //无论如何,都会执行的代码块 }
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.
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.
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.
● 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.
● 因为没有发生异常,所以catch代码块跳过。
● 执行finally代码块,输出日志,执行 ++temp
表达式.
● 返回try部分保存的值2.
五、Java异常类的几个重要方法
先来喵一眼异常类的所有方法,如下图:
Returns the detail message string of this throwable.
getMessage会返回Throwable的 detailMessage
属性,而 detailMessage
就表示发生异常的详细消息描述。
举个例子, FileNotFoundException
异常发生时,这个 detailMessage
就包含这个找不到文件的名字。
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的本地化描述。子类可以重写此方法,以生成特定于语言环境的消息。对于不覆盖此方法的子类,默认实现返回与相同的结果 getMessage()。
Returns the cause of this throwable or null if thecause is nonexistent or unknown.
返回此可抛出事件的原因,或者,如果原因不存在或未知,返回null。
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().
该方法将堆栈跟踪信息打印到标准错误流。
输出的第一行,包含此对象toString()方法的结果。剩余的行表示,先前被方法fillInStackTrace()记录的数据。如下例子:
java.lang.NullPointerException at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3)
六、自定义异常
自定义异常通常是定义一个继承自 Exception 类的子类。
那么,为什么需要自定义异常?
● Java提供的异常体系不可能预见所有的错误。
● 业务开发中,使用自定义异常,可以让项目代码更加规范,也便于管理。
下面是我司自定义异常类的一个简单demo
public class BizException extends Exception { //错误信息 private String message; //错误码 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; } }
跑个main方测试一下
public class TestBizException { public static void testBizException() throws BizException { System.out.println("throwing BizException from testBizException()"); throw new BizException("100","哥,我错了"); } public static void main(String[] args) { try { testBizException(); } catch (BizException e) { System.out.println("自己定义的异常"); e.printStackTrace(); } } }
运行结果:
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提供的一个新功能,它用于自动资源管理。
● 资源是指在程序用完了之后必须要关闭的对象。
● try-with-resources保证了每个声明了的资源在语句结束的时候会被关闭
● 什么样的对象才能当做资源使用呢?只要实现了java.lang.AutoCloseable接口或者java.io.Closeable接口的对象,都OK。
在 try-with-resources
出现之前
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
出现之后,使用资源实现
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
的好处
● 代码更加优雅,行数更少。
● 资源自动管理,不用担心内存泄漏问题。
八、异常链
我们常常会想要在捕获一个异常后抛出另一个异常,并且希望把原始异常的信息保存下来,这被称为异常链。
throw 抛出的是一个新的异常信息,这样会导致原有的异常信息丢失。在JDk1.4以前,程序员必须自己编写代码来保存原始异常信息。现在所有 Throwable
子类在构造器中都可以接受一个 cause(异常因由)
对象作为参数。
这个 cause
就用来表示原始异常,这样通过把原始异常传递给新的异常,使得即使当前位置创建并抛出了新的异常,也能通过这个异常链追踪到异常最初发生的位置。
使用方式如下:
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 构造器 public MyException(String message, Throwable cause) { super(message, cause); }
运行结果:
我们可以看到异常信息有保存下来的,如果把cause(也就是FileNotFoundException 的e)去掉呢,看一下运行结果:
可以发现,少了 Throwablecause
,原始异常信息不翼而飞了。
九、异常匹配
抛出异常的时候,异常处理系统会按照代码的书写顺序找出"最近"的处理程序。找到匹配的处理程序之后,它就认为异常将得到处理,然后就不再继续查找。
查找的时候并不要求抛出的异常同处理程序的异常完全匹配。派生类的对象也可以配备其基类的处理程序
看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"); } } }
运行结果:
catch(Annoyance a)会捕获Annoyance以及所有从它派生的异常。捕获基类的异常,就可以匹配所有派生类的异常
try { throw new Sneeze(); } catch(Annoyance a) { } catch(Sneeze s) { //这句编译器会报错,因为异常已由前面catch子句处理 }
十、Java常见异常
NullPointerException
空指针异常,最常见的一个异常类。简言之,调用了未经初始化的对象或者是不存在的对象,就会产生该异常。
ArithmeticException
算术异常类,程序中出现了除数为0这样的运算,就会出现这样的异常。
ClassCastException
类型强制转换异常,它是JVM在检测到两个类型间转换不兼容时引发的运行时异常。
ArrayIndexOutOfBoundsException
数组下标越界异常,跟数组打交道时,需要注意一下这个异常。
FileNotFoundException
文件未找到异常,一般是要读或者写的文件,找不到,导致该异常。
SQLException
操作数据库异常,它是Checked Exception(检查异常);
IOException
IO异常,一般跟读写文件息息相关,它也是Checked Exception(检查异常)。平时读写文件,记得IO流关闭!
NoSuchMethodException
方法未找到异常
NumberFormatException
字符串转换为数字异常
总结
这个总结独辟蹊径,以几道经典异常面试题结束吧,以帮助大家复习一下,嘻嘻。
● java 异常有哪几种,特点是什么?(知识点二可答)
● 什么是Java中的异常?(知识点一可答)
● error和exception有什么区别?(知识点二可答)
● 什么是异常链?(知识点八可答)
● try-catch-finally-return执行顺序(知识点四可答)
● 列出常见的几种RunException (知识点二可答)
● Java异常类的重要方法是什么?(知识点五可答)
● error和exception的区别,CheckedException,RuntimeException的区别。(知识点二可答)
● 请列出5个运行时异常。(知识点二可答)
● Java 7 新的 try-with-resources 语句(知识点七可答)
● 怎么自定义异常?(知识点六可答)
● 说一下常见异常以及产生原因(知识点十可答)
● 谈谈异常匹配(知识点九可答)
● 谈谈异常处理(知识点三可答)
本文来自 java入门 栏目,欢迎学习!
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!