Java异样类型及解决
前言: 异样指的是程序在执行过程中,呈现了非正常状况,导致了java
的jvm
进行进行。
异样构造为:
Throwable
为顶级父类
- 子类
Error
为重大报错 , - 子类
Exception
就是咱们所说的异样了
异样解决的关键字
java
中解决异样的有五个关键字: try、catch 、finally 、 throw 、throws
throw
抛出异样 , thorws
申明异样 , 捕捉异样 try_catch
throw
public class SegmentFault { public static void main(String[] args) { /** * throw 抛出异样 * 格局 - throw new 异样类名(参数); * */ // 创立一个数组 int [] arr = { 2, 4, 56 ,5}; // 依据索引找到对应的元素 int index = 4; int element = getElement(arr,index); System.out.println(element); System.out.println("owo"); // 运行谬误 无奈持续 } /** throw 抛出异样 揭示你必须解决 */ public static int getElement(int [] arr, int index){ // 判断数组索引是否越界 if (index < 0 || index > arr.length -1){ /** * 条件满足越界 当执行到throw抛出异样后就无奈运行,完结办法并且提醒 * */ throw new ArrayIndexOutOfBoundsException("数组下标越界异样"); } int element = arr[index]; return element; }}
异样后果为:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 数组下标越界异样
throws
public class SegmentFault{ public static void main(String [] args){ read("a.txt"); } public static void read(String path) throws FileNotFoundException, IOException { if (!path.equals("a.txt")){ // 如果没有a.txt // 如果不是 a.txt 该文件不存在 是一个谬误 也就是异样 throw throw new FileNotFoundException("文件不存在"); } if (!path.equals("b.txt")){ throw new IOException("文件不存在"); } } }
异样后果为:
Exception in thread "main" java.io.IOException: 文件不存在
try、catch、finally + Throwable中的罕用办法。
Throwable罕用办法如下printStackTrace() :
*打印异样详细信息。getMessage() :
获取异样起因。toString():
获取异样类型及形容信息。
public class Demo03 { public static void main(String[] args) { /** * try- catch 捕捉异样 * */ // 可能会生成的异样 try { // 捕捉或者申明 read("b.txt"); } catch (FileNotFoundException e) { // 应用某种捕捉,实现对异样的解决 System.out.println(e); /** * Throwable中的查看办法 * getMessage 获取异样信息 提醒给用户看的 * toString 获取异样的类型和异样形容(不必) * printStackTrace * */ System.out.println("Throwable罕用办法测试"); System.out.println(e.getMessage()); // 文件不存在 System.out.println(e.toString()); e.printStackTrace(); } finally { System.out.println("不论程序怎么,这里都会被执行"); } System.out.println("over"); } public static void read(String path) throws FileNotFoundException { if (!path.equals("a.txt")) { throw new FileNotFoundException("文件不存在"); } } }
输入后果为:
java.io.FileNotFoundException: 文件不存在
-----Throwable罕用办法测试------
文件不存在
java.io.FileNotFoundException: 文件不存在
不论程序怎么,这里都会被执行
over
注意事项 :try catch finally都不能够独自应用