8,异常处理

xiaoxiao2021-02-28  52

Throwable

1,Error,代表编译和系统类错误,不允许捕捉

2,RuntimeException,运行类异常,由运行时编译器引发的异常,发生在很多的地方,为了避免巨大的资源浪费,不捕捉

ArrayIndexOutOfBoundsException

ClassCastException

NumberFormatException字符串转化为数字

IllegalArgumentException

NullPointerException

3,  ArithmeticException FileNotFoundException IOException SQLException NoSuchMethodException OutOfMemoryError StackOverflowError package caokangnsd; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ThrowsAndCatch { /* * 异常处理 Throwable->Exception+ErrorException * 表示由于网络故障/文件损坏/设备错误/用户输入非法等情况导致的异常/这类异常是可以通过Java异常捕获机制处理的. * 而Error表示Java运行时环境出现的错误,例如:JVM内存溢出等. * IllegalArgumentException:抛出的异常表明向方法传递了一个不合法或不正确的参数 NullPointerException * ArrayIndexOutOfBoundsException ClassCastException NumberFormatException 非检测异常 * 检测异常 getMessage 包含Throwable异常的子类必须必父类小或者没有 */ static FileInputStream fis;

public static void test() { try { fis = new FileInputStream(""); } catch (FileNotFoundException e) {//catch // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (Exception e) {//catch Exception e.printStackTrace(); } finally {// finally的最后抛出 if (fis != null) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

public static void er(int a) throws ErException { if (a > 10) { throw new RuntimeException("比10大");//RuntimeException } else { throw new ErException("小于10");//自定义异常抛出 } } public static void main(String[] args) { test(); try { er(5); } catch (ErException e) {//捕获自定义异常 // TODO Auto-generated catch block e.printStackTrace(); } } } //继承Exception类新建自己的异常类 class ErException extends Exception { /** *  */ private static final long serialVersionUID = 1L; public ErException() { super(); // TODO Auto-generated constructor stub } public ErException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public ErException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public ErException(String message) { super(message); // TODO Auto-generated constructor stub } public ErException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }  

转载请注明原文地址: https://www.6miu.com/read-2624701.html

最新回复(0)