1. 异常
1.1 概述
-
异常:程序出现了不正常情况
-
Error:严重问题,不需要捕获
-
Exception:程序本身可以处理的异常
-
RuntimeException:编译期不检查
-
非RuntimeException:编译期检查修改,否则编译不通过
1.2 异常处理 try {} catch() {}
-
模板
try { 可能会出问题代码块; } catch (异常类名 e) { 处理例码; }
-
demo
public class DemoTry { public static void main(String[] args) { int[] a = {1,2,3,4}; System.out.println("开始"); try { System.out.println(a[12]); } catch (IndexOutOfBoundsException e) { System.out.println(e); e.printStackTrace(); } System.out.println("结束"); } }
1.3 异常抛出 throws 异常类名
-
定义格式
方法名()throws 异常类名
跟在方法定义后面{}前面 -
只是抛出了异常,并没有做处理,
-
编译时异常,要么抛出,要么处理
-
谁调用该方法谁处理,用
try{}catch(){}
处理 -
demo
public class DemoThrow { public static void main(String[] args) { int[] nums = new int[new Random().nextInt(100) + 1]; int a = 12; try{ a = getItem(nums, 56); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } System.out.println(a); } public static int getItem(int[] nums, int i) throws IndexOutOfBoundsException{ return nums[i]; } }
1.4 Throwable成员方法
方法名 | 说明 |
---|---|
public String getMessage() | 返回此 throwable 的详细消息字符串 原因 |
public String toString() | 返回此可抛出的简短描述 |
public void printStackTrace() | 把异常的错误信息输出在控制台 |
public class DemoTry02 {
public static void main(String[] args) {
int a = 12;
int c = 0;
try{
c = a / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
System.out.println(e);
System.out.println(e.toString());
e.printStackTrace();
}
System.out.println(c);
}
}
1.5 异常区别
-
编译时异常:又称受检异常,必须显示处理,否则无法通过编译
-
运行时异常:又称非受检异常,不必显示处理,也可以处理
-
demo
public class DemoQu { public static void main(String[] args) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String s = "1234-56-78"; Date date = new Date(); try { date = simpleDateFormat.parse(s); // 编译是异常 } catch (ParseException e) { e.printStackTrace(); } System.out.println(simpleDateFormat.format(date)); int[] a = {1,2,3,4,5}; try { System.out.println(a[13]); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } System.out.println(Arrays.toString(a)); } }
1.6 自定义异常类
public class DemoNumberException extends Exception{
public DemoNumberException() {
}
public DemoNumberException(String message) {
super(message);
}
}
import java.util.Random;
public class DemoNumberCheck {
public static boolean checkNumber(int num) throws DemoNumberException {
if (num < 20 || num > 70) {
throw new DemoNumberException();
} else if (num > 50) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int a = new Random().nextInt(100);
a = 88;
boolean st = false;
try {
st = checkNumber(a);
} catch (DemoNumberException e) {
e.printStackTrace();
}
if (st) {
System.out.println("good job");
} else {
System.out.println("wrong");
}
}
}
-
throw 和 throws 的区别
throws throw 方法名()后面 throws 异常类名 方法里面 throw 异常对象 表示一种可能性,不一定抛出 执行throw 一定抛出某个异常 谁调用方法谁处理异常 可以在方法内处理throw 抛出的异常