在计算机程序运行的过程中,会出现各种各样的错误。
异常Throwable:有两个体系Error错误类和Exception异常类。
Error:会导致虚拟机宕机。
常见的Error:OutOfMemoryError(内存溢出)、StackOverflowError(堆栈溢出)
Exception:可“捕获”可“处理”。Exception又分为RuntimeException(运行时异常)和Checked Exception(编译器异常)
RuntimeException无需强制捕获,非RuntimeException(Checked Exception)需强制捕获,或者用throws声明;
一、使用try...catch语句捕获异常
public class Demo01 {
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(n+10);
}catch(Exception ex) {
System.out.println("您输的输入有误!");
}
}
}
如果用户输入的不是int类型的整数,则给用户提示"您输的输入有误!"
需要注意的是:存放多个catch时,子类必须写在前面
二、 finally语句
finally语句不是必须的,可写可不写。Finally总是最后执行。用以下一段代码可以得出此结论:
public class Demo06 {
public static void main(String[] args) {
System.out.println(todo());
}
public static int todo() {
int n = 8;
int ret = 0;
try {
n = n / 0; //出现异常
ret = n * 10; //ret = 80;
return ret;
}catch(Exception ex) {
System.out.println("异常出现了~!");
ret = n + 10;
return ret;
}finally {
System.out.println("执行finally");
}
}
}
三、运行时异常(RuntimeException)
public class Demo07 {
public static void main(String[] args) {
String str = "浪漫主义诗人又醉倒在春风里他说遇见你的时候手里却没纸笔后来乘风而起看过人间八万里可是最美的黄昏却消失在⻘春里";
String ret = copy(str, 13, 26);
System.out.println(ret);
}
//复制字符串
public static String copy(String s, int beginIndex, int endIndex) {
if(s == null) {
//空指针
//手动创建NullPointerException异常对象,并"抛出"
NullPointerException npe = new NullPointerException();
throw npe; //抛出异常对象
}
if(beginIndex > endIndex) {
throw new IllegalArgumentException("开始下标不能大于结束下标!");
}
if(beginIndex < 0 || endIndex >= s.length()) {
throw new StringIndexOutOfBoundsException("下标超出目标字符串的范围!");
}
char[] arr = s.toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = beginIndex; i <= endIndex; i++) {
char c = arr[i];
sb.append(c);
}
return sb.toString();
}
}
如果数组为null出现NullPointerException;
如果beginIndex > endIndex 出现 IllegalArgumentException并提示用户开始下标不能大于结束下标!;
如果beginIndex<0或者endIndex>=数组的长度-1 出现StringIndexOutOfBoundsException 并提示用户"下标超出目标字符串的范围!";
如果按照代码没有出现异常,则在控制台输出:"他说遇见你的时候手里却没纸笔"。
四、Checked Exception(编译器异常)
自定义一个库存不足异常,当出库数量大于库存数量时,抛出异常并提示用户"库存不足"
public class Demo08 {
public static void main(String[] args) throws NotEnoughException {
System.out.println("原始库存数量:" + Reposistory.stock);
//入库
Reposistory.in(50);
System.out.println("入库50件后,库存数量:" + Reposistory.stock);
//出库
Reposistory.out(1000);
System.out.println("出库1000件后,库存数量:" + Reposistory.stock);
}
}
//仓库类
class Reposistory{
static int stock = 100;//库存数量
//入库
public static void in(int count) {
stock = stock + count;
}
//出库
public static void out(int count) throws NotEnoughException{
if(count > stock) {
throw new NotEnoughException();
}
stock = stock - count;
}
}
//自定义异常
//库存不足异常
class NotEnoughException extends Exception{
public NotEnoughException() {
super("库存不足!");
}
}
如果抛出RuntimeException运行时异常,可以省略异常类型的方法声明throws RuntimeException
如果抛出Checked Exception(编译器异常),必须完成异常类型的方法声明throws NotEnoughExceptionthrow
可以使用printStackTrace()可以打印异常的传播栈 。