java、exception

来源:互联网 发布:ios未越狱修改数据 编辑:程序博客网 时间:2024/06/16 17:30

如果某个函数中的代码有可能引发异常,可以使用try/catch块进行处理,这种处理方式成为“内部处理”

//自己抛异常,自己捕获异常//Exception类和其子类都是系统内置的异常,这些异常不一定总能捕获程序中发生的所有异常;有时候,我们可能要创建用户自定义的异常类;用户自定义异常类应该是Exception类的子类;import java.util.*;public class ThrowDemo {    public static void main(String[] args) {        try{            Scanner in = new Scanner(System.in);            int age = Integer.parseInt(in.nextLine());            if(age<0 || age>130){                throw new AgeException("年龄不合法....");            }        }catch(AgeException e){            e.printStackTrace();            System.out.println(e.getMessage());        }    }}class AgeException extends Exception{    public AgeException(){    }    public AgeException(String message){        super(message);    }}

这里写图片描述

如果不方便在函数内部进行处理,也可以将异常往函数外部传递,这就要使用到关键字throws;throws用于将函数内部产生的异常抛给主调(调用者)函数;

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Scanner;public class ThrowsDemo {    public static void main(String[] args){        Scanner in = new Scanner(System.in);        System.out.println("请输入用户名...");        String username = in.nextLine();//获取用户名        System.out.println("请输入年龄...");        int age = in.nextInt();//获取年龄        Student student = new Student();        student.setUsername(username);        try {            student.setAge(age);        } catch (AgeException e) {            e.printStackTrace();        }        System.out.println("学生姓名:"+student.getUsername()+"  学生年龄:"+student.getAge());    }}class Student{    private String username;    private int age;    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public int getAge() {        return age;    }    public void setAge(int age) throws AgeException {        if(age<0 || age>130){            throw new AgeException("年龄不合法");        }        this.age = age;    }}
 异常Exception分为检查型异常与非检查型异常; 检查型异常:在编译阶段jvm就必须要捕获的异常;非检查型异常(运行时异常):可捕获可不捕获; 可以使用try/catch/finally块,配合使用来处理异常; 如有多种类型的异常要进行处理,可以使用多重catch块 要手动发生异常,使用throw关键字; 任何抛到函数外部的异常,都必须使用throws关键字指定其异常类型;注意throw和throws的区别;自定义异常类一般继承于Exception类;Exception类是绝大部分异常类的父类,在异常类型不明的情况下,可以都认为是Exception
原创粉丝点击