java异常

异常的定义

(1)异常是程序执行期间发生的不常见的情况或事件,他们的出现会中断程序的执行,有些异常表示代码中的错误,修改这些错误,可以避免异常。。。
(2)异常就是有异于常态,和正常情况不一样,有错误出现。在java中,阻止当前方法或作用域的情况,称之为异常。

为什么要有异常,异常的作用

原文链接
**有问题我直接更改,改对就好了呀!大家看,出现问题,然后更改,那是不是首先你应该知道问题在哪里,如果没有异常来报错的话,是不是无法准确的去判断问题到底在哪里呢,所以这里是不是可以认为异常的作用就是指示出问题的代码块的位置及异常的内容呢!
第二个问题,有异常我们直接处理掉,就跟代码语法错了我们改正好了就行了呀,为什么还要throws抛出或者使用try…处理呢?其实你的程序写好了,要供别人去使用,这时也许你能保证你使用时不会出错,但是你能保证别人使用时不会出错吗?例如,对日期的解析:

public static void main(String[] args) {
    String str="2019-09-23 12:35:25";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        try {
            Date d=sdf.parse(str);
        } catch (ParseException e) {   //格式不一致就会产生异常,
            **System.out.println("你输入的格式不正确");**
        }
    }

对于这个程序,你是知道str的格式必须和sdf中的格式一致,否则会出错,而其他使用者在使用这个程序时,他也许不清楚的,输入错误导致两者不一致而出错,这时如果可以提示出出错的信息(比如"你输入的格式不正确"的信息)是不是就很明确和清晰了。

异常的处理

注意:虽然有异常处理机制,但程序中一定发生的事件不应该用异常处理机制。异常处理用于使系统从故障中恢复。
(1)当方法因为自生无法控制的原因而不能完成其他任务时
(2)文件不存在,网络连接无法建立时
(3)处理方法,类库,类中抛出的异常,如FileInputStream.read产生IOException
(4)在大的项目中采用统一的方式处理异常时
(5)编写文件处理器一类的程序时
(6)不经常发生但却可能发生的故障
!!!当异常发生时,程序通常就会中断,并输出一条信息。

注意:java语言提供的异常处理机制,有助于找到抛出的是什么异常,然后试着恢复它们,当可能发生受检异常时,必须处理它。
对于可能发生的受检异常有两种处理方式,方法内处理异常或是告诉方法的调用者处理。。

try-catch块:

public class Ex1 {

    public static void main(String[] args) {
        //要捕获的代码
        try{//含有可能抛出异常的代码
            int a=1/0;//产生了一个异常,抛出到main外面,如果不对运行时异常处理,1,则默认抛出。2.捕获
        }
        //捕获后的处理,捕获程序后向下运行
        catch (Exception e){   //每一个catch块中含有处理或捕获某种类型异常的代码
            System.out.println("报错了");
        }
        System.out.println("程序运行完了");

		try{
            int a=1/0;
        }
        catch (ArithmeticException e){ //作为一个对象,每个一场都有存取方法getMessage(),它返回抛出异常时创建的描述字符串。
            System.out.println(e.getMessage());
        }
        System.out.println("程序运行完了");
        
        try{
            int a=1/0;
        }
        catch (ArithmeticException e){
            e.printStackTrace();
        }
        System.out.println("程序运行完了");
    }
	
}

catch块执行完毕,执行它后面的语句,如果问题严重,则catch块可以调用exit()方法终止程序。
System.exit(0),参数0表示虽然遇到了一个严重的问题,但程序是正常结束的。

公共异常:Java预定义了一些常见异常
1、ArithmeticException
2,NullPointerException等等

异常的分类

在这里插入图片描述
注释:Error和RuntimeException属于Unchecked Exception(非检查异常);
try catch语句捕获多个异常时,如有诸如上述的继承关系,子类异常在前,父类的在后捕获。

     (1)Error:jvm中出现不可恢复的错误,如堆内存溢出等,程序是没有处理机会的。

     (2)运行时异常(RuntimeException):属于非检查异常,java编译器忽略其抛出和检查,当在加载运行后,出现的异常;常见有:ArrayIndexOutofException、NumberFormatException、NullPointerException、ClassCastException、ClassNotFoundException等。

     (3)非运行时异常:也叫可处理异常,程序编译时,就提示的异常。如:自定义异常、IOException、SQLException、FileNotFoundException等。

     (4)自定义异常示例:自定义异常根据需求使用throw关键字引发异常。

异常的抛出

1、定义 : 一个方法不处理这个异常,而是按调用层次向上传递,谁调用这个方法,这个异常就由谁来处理。

2、throw : 将产生的异常抛出(强调的是动作),抛出的既可以是异常的引用,也可以是异常对象。(位置: 方法体内)

3、throws : 如果一个方法可能会出现异常,但没有能力处理这种异常,可以在方法声明处用throws子句来声明抛出异常。用它修饰的方法向调用者表明该方法可能会抛出异常(可以是一种类型,也可以是多种类型,用逗号隔开)(位置: 写在方法名 或方法名列表之后 ,在方法体之前。)

注意 : 调用可能会抛出异常的方法,必须添加try-catch代码块尝试去捕获异常 或者 添加throws 声明 来将异常 抛出给更上一层的调用者进行处理,这里需要注意一个细节:新的异常包含原始异常的所有信息,根据这个我们可以去追溯最初异常发生的位置,

如下图所示
在这里插入图片描述

异常的抛出:
位置!!!!!!!!!!!是否或发生异常 !!!!!!!!!!! 作用
throw 出现在方法内部,后面跟异常对象 一定会发生异常 人为的触发一个异常
throws 出现在方法声明上 不一定发生 告诉方法的调用者有可能出现异常

创建自己的异常

注意:用户自定义的作用异常类都必须是Exception的子类。。在程序中发现一个异常情况时,可以抛出一个异常实例,将其放到异常队列中,并激活java的异常处理机制。。。

class myException extends Exception{
    private int detail;
    myException (int a){
        detail = a;
    }

    @Override
    public String toString() {
        return "myException[" +
                "detail=" + detail +
                ']';
    }
}

class ExceptionDemo{
    static void compute (int a) throws myException{
        System.out.println("Called compute("+ a + ".");
        if (a > 10) throw new myException(a);
        System.out.println("Normal exit");
    }

    public static void main(String [] args){
        try{
            compute(1);
            compute(20);
        } catch (myException e) {
            System.out.println("Exception caught" + e);
        }
    }

//运行结果
Called compute(1.
Normal exit
Called compute(20.
Exception caughtmyException[detail=20]

/**
 * 自定义异常:应用级异常*/
class AppException extends Throwable {
    private int errCode;
    private String errMsg;
    public AppException(int errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }
    /**
     * */
    public void setErrCode(int errCode){this.errCode = errCode; }

    public void setErrMsg(String errMsg){
        this.errMsg = errMsg;
    }
    public int getErrCode(){
        return this.errCode;
    }
    public String getErrMsg(){
        return this.errMsg;
    }
}

/*
* 自定义异常:系统级异常
* @author gavin*/
class SystemException extends Exception{
    private int errCode;
    private String errMsg;

    public SystemException(int errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    /**
     * */
    public void setErrCode(int errCode){
        this.errCode = errCode;
    }

    public void setErrMsg(String errMsg){
        this.errMsg = errMsg;
    }
    public int getErrCode(){
        return this.errCode;
    }
    public String getErrMsg(){
        return this.errMsg;
    }
}

class UserBean {

    private int userid;
    private String username;

    public UserBean(int userid, String username) {
        this.userid = userid;
        this.username = username;
    }

    public void setUserid(int userid){
        this.userid = userid;
    }

    public int getUserid(){
        return this.userid;
    }

    public void setUsername(String username){
        this.username = username;
    }

    public String getUsername(){
        return this.username;
    }
}

/**
 * 用户管理模块
 * */

public class UserManager {

    public void addUser(UserBean user) throws AppException,SystemException{
        //模拟系统故障
        try {
            int a=5/2;
            if ("admin".equals(user.getUsername())){
                throw new AppException(1002,"用户名不能是admin!");
            }
        }catch (Exception e){
            throw new SystemException(900,"系统故障,请稍后再试");
        }

        System.out.println("用户名新增成功");
    }
}

public class TestUser {

    public static void main(String[] args) {
        UserManager um = new UserManager();
        UserBean user = new UserBean(100,"zhanghaixia");
        try {
            um.addUser(user);
        } catch (AppException e) {
            System.out.println(e.getErrMsg());
        }catch (SystemException e){
            System.out.println(e.getErrMsg());
        }
    }
}

posted @ 2020-11-10 16:20  木有呂朋友  阅读(40)  评论(0)    收藏  举报