ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java异常学习

2021-03-03 21:32:19  阅读:61  来源: 互联网

标签:Java int System 学习 println 异常 public out


目录

1.什么是异常

  • 概念:程序在运行过程中出现的不正常现象。出现异常不处理将终止程序运行。
  • 异常处理的必要性:任何程序都可能存在大量的未知问题、错误;如果不对这些问题进行正确处理,则可能导致程序的中断,造成不必要的损失。
  • 异常处理:Java编程语言使用异常处理机制为程序提供了异常处理的能力。

2.异常的分类

Throwable:可抛出的,一切错误或异常的父类,位于java. lang包中。

  • Error: JVM、硬件、执行逻辑错误,不能手动处理。
    • StackOverflowError
    • OutOfMemoryError
  • Exception:程序在运行和配置中产生的问题,可处理。
    • RuntimeException:运行时异常,可处理,可不处理。
    • CheckedException:检查时异常,必须处理。(不属于类)

3.常见运行时异常

类型 说明
NullPointerException 空指针异常
ArrayIndexOutOfBoundsException 数组越界异常
ClassCastException 类型转换异常
NumberFormatException 数字格式化异常
ArithmeticException 算术异常
/**
 * 演示常见运行时异常
 * 运行时异常:RuntimeException及子类
 * 检查时异常:Exception及子类中除了RuntimeException以外都是检查时异常
 * @author ng
 */
public class Demo04 {
    public static void main(String[] args) {
        //运行时异常
        //1.NullPointerException
//        String name =null;
//        System.out.println(name.equals("zhangsan"));//所有对象没有初始化就进行调用就会出现空指针异常
        //2.ArrayIndexOutOfBoundsException
//        int[] arr={1,2,3};
//        System.out.println(arr[3]);//数组越界
        //3.ClassCastException
//        Object str="asdadds";
//        Integer integer=(Integer)str;//ClassCastException,Object对象是字符串,无法转换为数字
       // 4.NumberFormatException
//        int n=Integer.parseInt("100a");//NumberFormatException
        //5.ArithmeticException
        int n=10/0;
        
    }
}

4.异常的产生和传递

产生:当程序在运行时遇到不符合规范的代码或结果时,会产生异常或程序员使用throw关键字手动抛出异常。

传递:按照方法的调用链反向传递,如始终没有处理异常,最终会由JVM进行默认异常处理(打印堆栈跟踪信息)。

import java.util.Scanner;

/**
 * 演示异常的产生和传递
 * 要求:输入两个数字相除
 * @author NG
 */
public class Demo05 {
    public static void main(String[] args) {
        operation();
    }
    public static void operation(){
        System.out.println("=======operation=======");
        divide();
    }
    public static void divide(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入第一个数字");//输入一个a,出现异常没有处理,程序中断
        int num1=scanner.nextInt();
        System.out.println("请输入第二个数字");
        int num2=scanner.nextInt();
        int result=num1/num2;//num2=0,出现异常没有处理,所以程序中断
        System.out.println("结果"+result);
        System.out.println("程序执行完毕...");
    }
}
/*
=======operation=======
请输入第一个数字
10
请输入第二个数字
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.exception.Demo05.divide(Demo05.java:24)
	at com.exception.Demo05.operation(Demo05.java:16)
	at com.exception.Demo05.main(Demo05.java:12)

进程已结束,退出代码 1
*/

5.异常的处理

Java的异常处理是通过5个关键字来实现的:

  • try:执行可能产生异常的代码
  • catch:捕获异常,并处理
  • finally:无论是否发生异常,代码总能执行
  • throw:手动抛出异常
  • throws:声明方法可能要抛出的各种异常
/**
 * 演示try...catch...语句的使用
 * try{...可能发生异常的代码}
 * catch{...捕获异常并处理异常}
 * 有三种情况:(1)正常执行没有异常
 *            (2)出现异常并捕获(此时程序不会中断而是继续运行)
 *            (3)出现异常,不能捕获(比如出现了空指针异常,但是捕获的时候用的是数组越界异常)
 * @author NG
 */
public class Demo06 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int result= 0;
        try {
            System.out.println("请输入第一个数字");
            int num1=scanner.nextInt();
            System.out.println("请输入第二个数字");
            int num2=scanner.nextInt();
            result = num1/num2;
        } catch (Exception e) {//Exception:所有异常的父类
            e.printStackTrace();
            //e.getMessage();
        }
        System.out.println("结果"+result);
        System.out.println("程序执行完毕...");
    }
}
import java.util.Scanner;

/**
 * 演示try...catch...finally...的使用
 * finally{...不管有没有异常都会执行的代码...}
 * finally唯一不会执行的情况:手动退出JVM
 * @author NG
 */
public class Demo07 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int result= 0;
        try {
            System.out.println("请输入第一个数字");
            int num1=scanner.nextInt();
            System.out.println("请输入第二个数字");
            int num2=scanner.nextInt();
            result = num1/num2;
            //手动关闭JVM
            //System.exit(0);
        } catch (Exception e) {//Exception:所有异常的父类
            e.printStackTrace();
            //e.getMessage();
        }finally {
            System.out.println("释放资源...");
        }
        System.out.println("结果"+result);
        System.out.println("程序执行完毕...");
    }
}

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * 演示多重catch的使用
 * try{...}catch{...类型1...}catch{...类型2...}catch{...类型2...}...
 * 子类异常在前,父类异常灾后
 * 发生异常时按顺序诸葛匹配
 * 只执行第一个与异常类型匹配的catch语句
 * finally可以根据需要写或者不写
 */
public class Demo08 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int result= 0;
        try {
            System.out.println("请输入第一个数字");
            int num1=scanner.nextInt();
            System.out.println("请输入第二个数字");
            int num2=scanner.nextInt();
            result = num1/num2;
            //手动关闭JVM
            System.exit(0);
        } catch (ArithmeticException e) {//Exception:所有异常的父类
            System.out.println("算数异常");
            //e.getMessage();
        } catch (InputMismatchException e){
            System.out.println("输入不匹配异常");
        } catch (Exception e){
            System.out.println("未知异常");
        }
        System.out.println("结果"+result);
        System.out.println("程序执行完毕...");
    }
}

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * try...finally...的演示
 * 不能处理异常,可以释放资源,把异常向上抛出
 * @author NG
 */
public class Demo09 {
    public static void main(String[] args) {
        try {
            divide();
        } catch (Exception e) {
            System.out.println("出现异常"+e.getMessage());
        }
    }
    public static void divide(){
        Scanner scanner=new Scanner(System.in);
        int result= 0;
        try {
            System.out.println("请输入第一个数字");
            int num1=scanner.nextInt();
            System.out.println("请输入第二个数字");
            int num2=scanner.nextInt();
            result = num1/num2;
        } finally {
            System.out.println("释放资源");
        }
        System.out.println("结果"+result);
        System.out.println("程序执行完毕...");
    }
}

6.抛出异常

  • 如果在一个方法体中抛出了异常,如何通知调用者?
  • throws关键字:声明异常
  • 使用原则:底层代码向上声明或者抛出异常,最上层一定要处理异常,否则程序中断。
import java.util.Scanner;

/**
 * throws:声明异常
 * @author NG
 */
public class Demo10 {
    public static void main(String[] args) {
        try {
            divide();//divide()抛出异常,调用它的函数一定要处理异常,此处为main函数处理异常,亦可以由main函数把异常抛给JVM,JVM接收异常程序中断
        } catch (Exception e) {
           // e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
    public static void divide() throws Exception{
        Scanner scanner=new Scanner(System.in);
        int result= 0;
        System.out.println("请输入第一个数字");
        int num1=scanner.nextInt();
        System.out.println("请输入第二个数字");
        int num2=scanner.nextInt();
        result = num1/num2;
        System.out.println("结果"+result);
        System.out.println("程序执行完毕...");
    }
}
  • 除了系统自动抛出异常外,有些问题需要程序员自行抛出异常。
  • throw关键字:抛出异常
  • 语法:throw 异常对象;
public class Person {
    private String name;
    private String sex;
    private int age;

    public Person() {
    }

    public Person(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        if (sex.equals("男")||sex.equals("女")) {
            this.sex = sex;
        } else {
            throw new RuntimeException("性别输入错误");
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age>0&&age<=120) {
            this.age = age;
        }else{
            //抛出异常
            throw new RuntimeException("年龄不符合要求");
        }
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

}
//测试类
public class TestPerson {
    public static void main(String[] args) {
        Person person=new Person();
        person.setSex("adadf");//抛出异常
        person.setAge(260);
        System.out.println(person.toString());
    }
}

//如果抛出检查时异常,一定要处理异常,可以向上抛出,也可以在内部处理
public void setAge(int age) throws Exception{
        if (age>0&&age<=120) {
            this.age = age;
        }else{
            //抛出异常
            throw new Exception("年龄不符合要求");
        }
    }

7.自定义异常

  • 需继承自Exception或Exception的子类,常用RuntimeException。
  • 必要提供的构造方法:
    • 无参数构造方法
    • String message参数的构造方法
/**
 * 自定义异常
 * (1)继承Exception或者其子类,常用RunTimeException
 * @author NG
 */
public class AgeException extends RuntimeException {
    public AgeException() {
    }

    public AgeException(String message) {
        super(message);
    }

    public AgeException(String message, Throwable cause) {
        super(message, cause);
    }

    public AgeException(Throwable cause) {
        super(cause);
    }

    public AgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

//Person类中抛出异常
public void setAge(int age) {
        if (age>0&&age<=120) {
            this.age = age;
        }else{
            //抛出异常
            throw new AgeException("年龄不符合要求");
        }
    }

8.方法重写

带有异常声明的方法覆盖:

  • 方法名、参数列表、返回值类型必须和父类相同。
  • 子类的访问修饰符和父类相同或是比父类更宽。
  • 子类中的方法,不能抛出比父类更多、更宽的检查时异常。
public class Animal {
    public void eat() throws Exception{
        System.out.println("动物在吃");
    }
}
public class Dog extends Animal {
    @Override
    public void eat() throws Exception {
        System.out.println("狗在吃");
    }
}

Dog.eat()抛出的异常比Animal.eat()抛出的异常类更多、更宽。

标签:Java,int,System,学习,println,异常,public,out
来源: https://www.cnblogs.com/Ng3061851/p/14477039.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有