Java中怎么实现异常处理

发布时间:2021-08-06 14:45:40 作者:Leah
来源:亿速云 阅读:123

这篇文章给大家介绍Java中怎么实现异常处理,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

异常的定义

在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)

1. 异常的体系结构

Java程序在执行过程中所发生的异常事件可分为两类:

异常的体系结构
 * java.lang.Throwable
 * 		|-----java.lang.Error:一般不编写针对性的代码进行处理。
 * 		|-----java.lang.Exception:可以进行异常的处理
 * 			|------编译时异常(checked)不会生成字节码文件
 * 					|-----IOException
 * 						|-----FileNotFoundException
 * 					|-----ClassNotFoundException
 * 			|------运行时异常(unchecked,RuntimeException)
 * 					|-----NullPointerException//空指针异常
 * 					|-----ArrayIndexOutOfBoundsException//数组角标越界
 * 					|-----ClassCastException//类型转化异常
 * 					|-----NumberFormatException//编码格式异常
 * 					|-----InputMismatchException//输入不匹配
 * 					|-----ArithmeticException//算术异常

java中异常类的继承关系

Java中怎么实现异常处理

2. 按照异常发生的时间可以分为两类

Java中怎么实现异常处理

3.常见的异常类型

//******************以下是运行时异常***************************
//ArithmeticException
@Test
public void test6(){
    int a = 10;
    int b = 0;
    System.out.println(a / b);
}

//InputMismatchException
@Test
public void test5(){
    Scanner scanner = new Scanner(System.in);
    int score = scanner.nextInt();
    System.out.println(score);

    scanner.close();
}

//NumberFormatException
@Test
public void test4(){

    String str = "123";
    str = "abc";
    int num = Integer.parseInt(str);	
}

//ClassCastException
@Test
public void test3(){
    Object obj = new Date();
    String str = (String)obj;
}

//IndexOutOfBoundsException
@Test
public void test2(){
    //ArrayIndexOutOfBoundsException
    //		int[] arr = new int[10];
    //		System.out.println(arr[10]);
    //StringIndexOutOfBoundsException
    String str = "abc";
    System.out.println(str.charAt(3));
}

//NullPointerException
@Test
public void test1(){		
    //		int[] arr = null;
    //		System.out.println(arr[3]);

    String str = "abc";
    str = null;
    System.out.println(str.charAt(0));

}

//******************以下是编译时异常***************************
@Test
public void test7(){
    //		File file = new File("hello.txt");
    //		FileInputStream fis = new FileInputStream(file);
    //		
    //		int data = fis.read();
    //		while(data != -1){
    //			System.out.print((char)data);
    //			data = fis.read();
    //		}
    //		
    //		fis.close();

}

异常的处理

1. java异常处理的抓抛模型

**过程一:"抛"**程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。并将此对象抛出。一旦抛出对象以后,其后的代码就不再执行。

关于异常对象的产生:

**过程二:"抓"**可以理解为异常的处理方式:① try-catch-finallythrows

2.异常处理方式一:try-catch-finally

2.1 使用说明:
try{
    //可能出现异常的代码

}catch(异常类型1 变量名1){
    //处理异常的方式1
}catch(异常类型2 变量名2){
    //处理异常的方式2
}catch(异常类型3 变量名3){
    //处理异常的方式3
}
....
    finally{
        //一定会执行的代码
    }

使用说明:

如何看待代码中的编译时异常和运行时异常?

2.2. finally的再说明:

3. 异常处理方式二:

throws + 异常类型 写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。 一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足 throws 后异常类型时,就会被抛出。异常代码后续的代码,就不再执行!

4. 对比两种处理方式

try-catch-finally 真正的将异常给处理掉了。 throws 的方式只是将异常抛给了方法的调用者。并没真正将异常处理掉。

5. 开发中应该如何选择两种处理方式?

补充: 方法重写的规则之一: 子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型

手动抛出异常对象

1.使用说明

在程序执行中,除了自动抛出异常对象的情况之外,我们还可以手动的 throw 一个异常类的对象。

2.经典面试题

throwthrows区别: throw 表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。 throws 属于异常处理的一种方式,声明在方法的声明处。

3.代码示例

class Student{

    private int id;

    public void regist(int id) throws Exception {
        if(id > 0){
            this.id = id;
        }else{
            //手动抛出异常对象
            //			throw new RuntimeException("您输入的数据非法!");
            //			throw new Exception("您输入的数据非法!");
            throw new MyException("不能输入负数");

        }		
    }

    @Override
    public String toString() {
        return "Student [id=" + id + "]";
    }

}

自定义异常类

1.如何自定义异常类

2.代码示例

public class MyException extends Exception{

    static final long serialVersionUID = -7034897193246939L;

    public MyException(){

    }

    public MyException(String msg){
        super(msg);
    }
}

关于Java中怎么实现异常处理就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Java中的异常处理
  2. 如何在java7中实现异常处理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Apollo中怎么实现分布式配置中心

下一篇:如何解决某些HTML字符打不出来的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》