异常的作用:增强程序的健壮性
所有的异常类是从 java.lang.Exception 类继承的子类。
Exception 类是 Throwable 类的子类。除了Exception类外,Throwable还有一个子类Error 。
Java 程序通常不捕获错误。错误一般发生在严重故障时,它们在Java程序处理的范畴之外。
Error 用来指示运行时环境发生的错误。
例如,JVM 内存溢出。一般地,程序不会从错误中恢复。
异常类有两个主要的子类:IOException 类和 RuntimeException 类。
1.简单示例
public class Demo1_exception {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
try {
System.out.println(arr[10]);
}/*catch (ArrayIndexOutOfBoundsException index){
System.out.println("索引越界");
}*/catch (Exception e){
System.out.println("老大");
}
}
}
2.抛异常
下面定义一个person类,规定年龄在18-50之间,超出的话就向上抛异常
代码:
public class Demo3_thorw {
public static void main(String[] args) throws Exception {
Person p1 = new Person();
p1.setName("张阿三");
p1.setAge(90);
System.out.println(p1.getAge());
}
}
class Person{
private String name;
private int age;
public Person(){}
public Person(String name,int age){
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) throws AgeOutOfBoundsException{
if (age>=18 && age<=50) {
this.age = age;
}else{
throw new AgeOutOfBoundsException("年龄非法");
}
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
自定义异常:
class AgeOutOfBoundsException extends Exception{
public AgeOutOfBoundsException(String message) {
super(message);
}
}
3.finally详解
finally控制的语句一定会执行,前面遇到return也不会结束,除非退出虚拟机,system.exit(0)
用于释放资源,在io流和数据库中出现
final:修饰类不能被继承,修饰方法不能被重写,修饰变量只能被赋值一次
finalize:垃圾回收器
千万不要在fianlly里面写返回语句
代码:
public class Demo4_finally {
/*
* finally控制的语句一定会执行,前面遇到return也不会结束,除非退出虚拟机,system.exit(0)
* 用于释放资源,在io流和数据库中出现
* final:修饰类不能被继承,修饰方法不能被重写,修饰变量只能被赋值一次
* finalize:垃圾回收器
* 千万不要在fianlly里面写返回语句
* */
public static void main(String[] args) {
try {
System.out.println(10/0);
}catch (Exception e){
System.out.println("error");
return;
}finally {
System.out.println("finally");
}
}
}