解析:
Throwable类,是Error类和Exception类的父类,该对象由JVM生成且由JVM抛出,该来的子类可以作为catch参参数类型。
功能方法:
Error类:
Error类是Throwable子类,表示严重错误。该错误不应该被捕获。通过更改代码来解决该错误。
public class Demo4 {
public static void main(String[] args) {
int i = Integer.MAX_VALUE;
System.out.println(i);
int [] arr = new int[i];//java.lang.OutOfMemoryError
//当Java虚拟机由于内存不足而无法分配对象时抛出,并且垃圾收集器不再有可用的内存。
}
}
Exception类:
它是Throws类的子类,该对象应该被catch块所捕获,进行处理。该对象分成两种,一种称之为(编译)异常,另一种称为运行时异常。运行时异常就是RuntimExcption类及其子类。除此之外都是编译异常。
public class Demo5 {
public static void main(String[] args) throws FileAlreadyExistsException {
//编译异常
try {
FileInputStream in = new FileInputStream("");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//问题:该代码没有错误,但是编译通过,该异常就是编译异常也称之为检查异常。
//解决:声明异常,才能运行。
}
}
public class Demo6 {
public static void main(String[] args) throws Exception {
int i = 10;
try{
int res=i/0;
}catch (Exception e){
e.printStackTrace();
}
}
//问题:i/0 通过编译,能够直接运行,运行时出现异常错误,这种异常称为运行时异常。
//解决:声明异常(Exception类声明所有异常),有异常处理(Exception类捕获所有异常)
}
练习:定义人类,要求其年龄必须在1~100之间。
package day16;
import java.util.IllformedLocaleException;
class Person extends RuntimeException{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws IllformedLocaleException {
if(age>=1&&age<=100) {
this.age = age;
}else{
throw new IllformedLocaleException("输入的年龄有误!");
//问题:Integer取值范围涵盖1~100所以JVM不会由于超出Integer取值范围而
//抛出错误。
//解决:手动生成异常抛出,通过实例化时提供字符串阐述详细描述。
}
}
}
public class Demo7 {
public static void main(String[] args) {
Person person = new Person();
person.setAge(120);
}
}
throw关键字:表示抛出异常。用于抛出异常对象。
运行时自定义异常类:
class WrongAgeException extends RuntimeException{
//成员
public WrongAgeException(String message) {
super(message);
}
}
练习:定义学生类,要求其性别必须是男或者女,否则就抛出异常。
package day16;
class SrongSexException extends Exception {
public SrongSexException(String message) {
super(message);
}
}
class Study{
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) throws SrongSexException {
if(sex.equals("男")&&sex.equals("女")) {
this.sex = sex;
}else{
throw new SrongSexException("你输入性别有误!");
}
}
}
public class Demo8 {
public static void main(String[] args) throws SrongSexException {
Study study = new Study();
study.setSex("1");//Exception in thread "main" day16.SrongSexException:
// 你输入性别有误!
}
}