您的位置 首页 java

怎么解决Java中的异常呢?

1. java 异常引入

异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。

比如说,你的代码少了一个 分号 ,那么运行出来结果是提示是错误 Java .lang.Error ;如果你用 System .out.println(11/0) ,那么你是因为你用0做了除数,会抛出 java.lang. Arithmetic Exception 的异常。

异常发生的原因有很多,通常包含以下几大类:

  • 用户输入了非法数据。
  • 要打开的文件不存在。
  • 网络通信 时连接中断,或者 JVM 内存溢出。

这些异常有的是因为用户错误引起,有的是程序错误引起的,还有其它一些是因为物理错误引起的。

要理解Java异常处理是如何工作的,你需要掌握以下三种类型的异常:

  • 检查性异常(编译异常):最具代表的检查性异常是用户错误或问题引起的异常,这是 程序员 无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。
  • 运行时异常: 运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
  • 错误: 错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。

运行时异常编译器无法检测但是需要尽量避免,编译异常是编译器要求必须处理的异常

2.一个简单的异常处理

运行时异常:

 <pre class="prettyprint hljs dart" style=" padding : 0.5em; font-family: Menlo, Monaco, Consolas, " Courier  New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block;  margin : 0px 0px 1.5em; font-size: 14px;  line-height : 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;  text-decoration -style: initial; text-decoration-color: initial;">int num1 = 10;
int num2 = 0;
try { 
    int res = num1 / num2;
} catch (java.lang. Exception  e) { 
    throw new RuntimeException(e);
}</pre>
  

可以通过选中代码块快捷键ctrl + alt + T快速生成异常

3.java的异常体系

所有的异常类是从 java.lang.Exception 类继承的子类。

Exception 类是 Throwable 类的子类。除了 Exception 类外, Throwable 还有一个子类 Error

Java 程序通常不捕获错误。错误一般发生在严重故障时,它们在Java程序处理的范畴之外。

Error 用来指示运行时环境发生的错误。

例如,JVM 内存溢出。一般地,程序不会从错误中恢复。

异常类有两个主要的子类: IOException 类和 RuntimeException 类。

编译异常和运行时异常所处的阶段:

4.五大运行时异常

NullPointerException

当应用程序试图在需要对象的地方使用 null 时,抛出该异常

 <pre class="prettyprint hljs cs" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 * 空指针异常
 */
public   static    void   nullPointerException()  { 
     String  name = null;
    System.out.println(name.length());
}</pre>
  

ArithmeticException

当出现异常的运算条件时,抛出此异常。例如,一个整数”除以零”时,抛出此类的一个实例。

 <pre class="prettyprint hljs cpp" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 * 数学运算异常,示例:除0异常
 */
public  static  void  divideByZero()  { 
    // 引入异常的基本使用
    int num1 = 10;
    int num2 = 0;
    try { 
        int res = num1 / num2;
    } catch (java.lang.Exception e) { 
        throw new RuntimeException(e);
    }
}</pre>
  

ArrayIndexOutOfBoundsException

用非法索引访问数组时抛出的异常。如果 索引 为负或大于等于数组大小,则该索引为非法索引。

 <pre class="prettyprint hljs cs" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 * 数组越界异常
 */
public  static  void  arrayIndexOutOfBoundsException()  { 
    int[] arr = { 1,2,3};
    System.out.println(arr[3]);
}</pre>
  

ClassCastException

当试图将对象强制转换为不是实例的子类时,抛出该异常。

 <pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">class  A  { }
class  B   extends   A  { }
class  C  extends  A  { }

/**
 * 类型转换异常
 */
public static void classCastException() { 
    A b = new B(); // 向上转型
    C c = (C)b;
}</pre>
  

number FormatException

当应用程序试图将 字符串 转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。

 <pre class="prettyprint hljs dart" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 * 数字格式不正常异常
 */
public static void numberFormatException() { 
    String name = "12我的";
    int num = Integer.parseInt(name);
}</pre>
  

5.编译异常

常见的编译异常:

6.异常处理机制

try – catch

使用 try catch 关键字可以捕获异常。 try/catch 代码块放在异常可能发生的地方。

try/catch 代码块中的代码称为保护代码,使用 try/catch 的语法如下:

 <pre class="prettyprint hljs xquery" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">try
{ 
   // 程序代码
}catch(ExceptionName e1)
{ 
   //Catch 块
}</pre>
  

Catch 语句包含要捕获异常类型的声明。当保护代码块中发生一个异常时, try 后面的 catch 块就会被检查。

如果发生的异常包含在 catch 块中,异常会被传递到该 catch 块,这和传递一个参数到方法是一样。

  • 如果异常发生了,则异常发生后面的代码块不会执行,直接进入到 catch

多重捕获块::sparkles:

一个 try 代码块后面跟随多个 catch 代码块的情况就叫多重捕获。

多重捕获块的语法如下所示:

 <pre class="prettyprint hljs xquery" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">try{ 
   // 程序代码
}catch(异常类型1 异常的变量名1){ 
  // 程序代码
}catch(异常类型2 异常的变量名2){ 
  // 程序代码
}catch(异常类型3 异常的变量名3){ 
  // 程序代码
}</pre>
  

上面的代码段包含了 3 个 catch 块。

可以在 try 语句后面添加任意数量的 catch 块。

如果保护代码中发生异常,异常被抛给第一个 catch 块。

如果抛出异常的数据类型与 ExceptionType1 匹配,它在这里就会被捕获。

如果不匹配,它会被传递给第二个 catch 块。

如此,直到异常被捕获或者通过所有的 catch 块。

注意:多个 catch 捕获异常的情况,子类要放在前面,父类在后面

finally关键字:說

finally 关键字用来创建在 try 代码块后面执行的代码块。

无论是否发生异常, finally 代码块中的代码总会被执行。(适用于发生异常的资源释放场景)

finally 代码块中,可以运行清理类型等收尾善后性质的语句。

finally 代码块出现在 catch 代码块最后,语法如下:

 <pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">try{ 
  // 程序代码
}catch(异常类型1 异常的变量名1){ 
  // 程序代码
}catch(异常类型2 异常的变量名2){ 
  // 程序代码
}finally{ 
  // 程序代码
}</pre>
  

对于运行时异常,如果没有显式的使用try-catch处理异常,则默认采用 throws 的方法向上抛出异常,直到抛到JVM虚拟机,JVM虚拟机会选择摆烂,显示异常信息,退出程序路‍♂️

throws/throw 关键字

如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明。 throws 关键字放在方法签名的尾部。

也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。

实例:

 <pre class="prettyprint hljs cpp" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 * 文件流异常,throws演示
 */
public  static  void  fileError()  throws  FileNotFoundException  { 
    FileInputStream fis = new FileInputStream("d://test.txt");
}</pre>
  
  • 子类重写父类的方法时,对于抛出异常的规定:子类重写的方法,所抛出的异常要么和父类的方法一致,要么为父类方法异常的子类型
  • throws try-catch 最好不要共存
  • 当一个方法调用另一个方法,而另一个方法存在抛出的 编译异常 (非运行异常)的时候,此方法也应该抛出一个异常
 <pre class="prettyprint hljs java" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">public  static  void  fileErrorTest()  throws  FileNotFoundException  { 
    fileError();
}
public  static  void  fileError()  throws  FileNotFoundException  { 
    FileInputStream fis = new FileInputStream("d://test.txt");
}</pre>
  

throw和throws的区别:

7.自定义异常

在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。

 <pre class="hljs nginx" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Throwable
Exception
RuntimeException
</pre>
  

首先,写一个异常类:

 <pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 *  自定义异常
 */
class  AgeException  extends  RuntimeException  { 
    public AgeException(String message) { 
        super(message);
    }
}</pre>
  

使用该异常类:

 <pre class="prettyprint hljs cpp" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
 * 自定义异常
 */
public  static  void  customException()  { 
    int age = 12;
    if (!(age >= 18)) { 
        throw new AgeException("您还未成年!");
    }
}</pre>  

文章来源:智云一二三科技

文章标题:怎么解决Java中的异常呢?

文章地址:https://www.zhihuclub.com/183004.shtml

关于作者: 智云科技

热门文章

网站地图