异常
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ef1beb74b1c225a6a4b3b13d410f9915.png)
空指针 null 空对象调用方法
索引越界异常 超过了数组的边界
数字运算异常
异常:程序出现了非正常情况
特点:
1.异常信息以红色字体打印在控制台
2.会影响后续代码的执行 -- JVM非正常停止
Throwable
1.Error
StackOverFlowError 栈溢出
OutOfMemoryError 堆溢出
2.Exception
RuntimeException 运行时异常、
除了RuntimeException以外 为编译期异常
抛异常
创建了异常对象,阻止程序运行,以红色字体将异常信息打印在看控制台
异常信息:
异常类的描述
出现异常的原因
异常出现的位置
编译期异常:
编译期出现的,必须做处理,否则程序无法执行
处理方式
捕获 try catch
声明 throws
public class Test{
public static void main(String[] args){
try{
divide(2, 0);
}catch (ArithmeticException e){
System.out.printIn("出现异常,除数为0");
}
System.out.printIn("后续代码执行了...");
}
public static int divide(int a, int b){
return a/ b;
}
}
异常之finally
public class Test {
public static void main(String[] args) {
try {
System.out.println("①");
} catch (NullPointerException e) {
System.out.println("②");
}
finally {
System.out.println("③");
}
System.out.println("④");
}
public static int divide(int a, int b){
return a/ b;
}
}
异常之throws
"""
声明异常:
作用能够可能出现编译的异常通过编译
"""
public class Test {
public static void main(String[] args) throws Exception, RuntimeException {
divide(2, 0);
}
public static void show2(){
try {
divide(4, 2);
System.out.println("①");
} catch (Exception e) {
System.out.println("②");
}
System.out.println("③");
}
public static int divide(int a, int b) throws Exception{
return a /b;
}
}
异常之throw
public class Test {
public static void main(String[] args) {
test(10 );
}
public static void test(int num){
if(num == 1){
throw new RuntimeException("num为1...");
}
}
}
异常之自定义(必须继承自Exception)
异常案例
public class AgeOutOfBoundsException extends RuntimeException{
public AgeOutOfBoundsException(){
}
public AgeOutOfBoundsException(String message) {
super(message);
}
}
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
if(age<18||age>25){
throw new AgeOutOfBoundsException("年龄不合法...");
}else{
this.age = age;
}
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生姓名:");
String name = sc.next();
Student stu = new Student();
stu.setName(name);
while(true){
System.out.println("请输入学生年龄:");
int age = sc.nextInt();
try{
stu.setAge(age);
break;
}catch (AgeOutOfBoundsException e){
System.out.println(e.getMessage());
continue;
}
}
System.out.println(stu);
}
}