Java异常总结

异常的简介:

异常就是错误对象。
编译时异常:再书写代码时出现的错误
运行时异常:在执行代码时出现的错误
抛异常:创建一个错误对象,把对象丢出来
捕获异常:默认是jvm来捕获,如果jvm捕获到程序会中断。

public class Test{
	public static void main(String [] args){
	System.out.println(1/0);
	}
}

异常的分类

1.RuntimeException:运行时异常,一般不手动处理,出问题了再处理。
2.其他Exception:必须要经过手动处理。
3.Error:一般指的是系统级错误。
在这里插入图片描述

异常的处理-try…catch

try{
尝试执行的代码
}catch(Exception e){
处理异常的代码
}finally{
最终的
}

package com.xyq.entity;

public class Cat extends Animal {

    public static void main(String[] args) {
        try {
            System.out.println(1/1);
        }catch (Exception e){
            System.out.println("管理员,出错了");
        }finally {
            System.out.println("我是fally");
        }
    }
}

异常的处理-throws和throw

警告:产生的错误尽可能的自己处理,少向外抛出异常。
throws 表示方法准备要扔出一个异常
throw 表示向外抛出异常

package com.xyq.entity;

public class Animal {
    public static void chu(int a,int b)throws Exception{
        if (b==0){
           throw new Exception("你不可以给我0");//真正的向外抛出一个异常
        }else {
            System.out.println(a/b);
        }
    }
    public static void main(String[] args) {

        try {
            chu(2,1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

自定义异常:
直接继承Exception或者RuntimeException来实现自定义异常

package Abnormal.CustomExceptions;

public class Person {
    String name;
    String gender;
    public Person(String name,String gender){
        this.name = name;
        this.gender = gender;

    }
}

package Abnormal.CustomExceptions;

public class ZaoTangZi {
    public void nan(Person p)throws GenderException{
        if (p.gender.equals("男")){
            System.out.println("欢迎光临");
        }else{
            throw new GenderException("性别不对,这里是男澡堂子");
        }
    }
}

package Abnormal.CustomExceptions;

public class GenderException extends Exception{//自己定义的异常必须继承Exception或者.RuntimeException
    public GenderException(String msg){
        super(msg);//调用父类的构造方法Exception(msg)
    }
}

package Abnormal.CustomExceptions;

public class Test {
    public static void main(String[] args)throws GenderException {
        Person p1 = new Person("张无忌","男");
        Person p2 = new Person("赵敏","女");
        ZaoTangZi ztz = new ZaoTangZi();
        ztz.nan(p2);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值