JAVA异常之异常处理

来源:互联网 发布:撞库软件下载 编辑:程序博客网 时间:2024/04/30 06:43

一、常见的异常

public class ExceptionDemo01 {public static void main(String[] args) {//1.java.lang.NullPointerException空指针异常/*String str = null;System.out.println(str.length());*///2.java.lang.ArrayIndexOutOfBoundsException数组索引越界异常/*int[] arr  =new int[10];arr[10]=10;*///3.java.lang.IndexOutOfBoundsException索引越界异常/*List list = new ArrayList<>();list.get(0);*///4.java.lang.ArithmeticException算术异常/*System.out.println(10/0);*///5.java.lang.NumberFormatException数据格式化异常/*String str = "abv";Integer.parseInt(str);*///6.java.util.InputMismatchException输入不匹配异常/*Scanner scan = new Scanner(System.in);int a = scan.nextInt();*///7.java.lang.ClassCastException类转化异常}}
二、解决异常

① 抛给上一级(并未解决异常)

② try catch

public class ExceptionDemo02 {public static void main(String[] args) {String str = null;int [] arr = new int[10];try{arr[10]=10;}catch(NullPointerException e){e.printStackTrace();System.out.println("发生了空指针异常");}catch (ArrayIndexOutOfBoundsException e) {e.printStackTrace();System.out.println("发生了数组越界异常");}catch (Exception e) {//总会执行的语句}System.out.println("************");}}
三、自定义异常

public class MyException extends Exception{public MyException(String msg){super(msg);}}public class ExceptionDemo03 {public static void main(String[] args) {int age = 150;if(age<0 || age>100){try {throw new MyException(String.valueOf(age));} catch (MyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}