编程语言
首页 > 编程语言> > Java异常处理机制(捕获异常、自定义异常)

Java异常处理机制(捕获异常、自定义异常)

作者:互联网

异常处理机制

一、异常概念

异常是程序在编译或运行过程出现的例外,这些例外在有的可以避免有的却无法避免

二、异常分类

检查异常也称为编译期异常

未检查异常也称为运行时异常

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CcsuFAwN-1627285642364)(C:/Users/lenovo/AppData/Roaming/Typora/typora-user-images/image-20210726140833377.png)]

常见异常:
数组下标越界异常:ArrayIndexOutOfBoundsException
字符串下标越界异常:StringIndexOutOfBoundsException
解析异常:ParseException
数字格式化异常:NumberFormatException
输入不匹配异常:InputMismatchException
文件找不到异常:FileNotFoundException
算术异常:ArithmeticException
空指针异常:NullPointerException
没有这样的元素异常:NoSuchElementException
类型转换异常:ClassCastException

栈溢出异常:StackOverfflowError

异常:

AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException, DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException, InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException, InvocationTargetException, IOException, JAXBException, JMException, KeySelectorException, LastOwnerException, LineUnavailableException, MarshalException, MidiUnavailableException, MimeTypeParseException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ScriptException, ServerNotActiveException, SOAPException, SQLException, TimeoutException, TooManyListenersException, TransformerException, TransformException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URIReferenceException, URISyntaxException, UserException, XAException, XMLParseException, XMLSignatureException, XMLStreamException, XPathException

三、异常处理方式

Java编译期异常必须要进行处理,否则Java源文件在编译时编译器会提示错误,且源文件无法成功编译

Java编译期异常的处理方式有两种

使用try、catch、finally捕获异常
try{
//可能会出现异常的代码
//如果异常,内部任何程序都不会执行、
return;
}catch(ParseException e){
//捕获执行的代码
}finally{
//不管是否发生异常都要执行的代码
return;
}
先执行finally里的,后执行try里的。

实例演示:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Yichang {
    public static void main(String[] args) throws ParseException,ClassCastException {

        //异常处理
        //1、方法头抛异常 throws  ,调用方法的时候还要处理.  //throws ParseException
        //可以抛多个异常,异常之间用逗号隔开。可抑制结抛Exception
        //2、try{}catch(){}finally{}
        test01();
        test02();


    }
    //第一种
    public static  void test01() throws ParseException {
        SimpleDateFormat ne = new SimpleDateFormat("yyyy-MM-dd");
        Date date = ne.parse("2021-02-02");
        System.out.println(date);
    }

    //第二种
    public static  void test02(){
        SimpleDateFormat ne = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = ne.parse("aa");
        } catch (ParseException e) {
            e.printStackTrace();//打印异常信息
            e.getMessage();
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            //一定会执行,//回收资源
            System.out.println("ca,大哥!");
        }
    }
}

运行结果:
请添加图片描述

四、自定义异常

在开发中,可能需要自定义异常类。
自定义异常根据继承的父类不同分为两类:

继承自Exception的自定义异常为编译期异常必须要进行处理

继承自RuntimeException的自定义异常为运行时异常不需要进行特别的处理。

五、练习(自定义异常)

自定义一个学生类,属性有 姓名 年龄,如果用户在给学生年龄赋值时,年龄小于0抛出一个Age_0Exception ,大于150 抛出一个Runti

创建异常类(运行时异常):

public class Runti extends RuntimeException{
    //运行时异常
    public Runti() {
    }

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

创建异常类(编译时异常):

public class Age_0Exception extends Exception{
    //编译类异常

    public Age_0Exception() {
//        super();   不加也会默认加
    }

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

捕获异常:

public class ZidingyiClasee {
    private  int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws Age_0Exception,Runti {
        if(age<0){
//          Age_0Exception ag = new Age_0Exception("年龄小于0");
            throw new Age_0Exception("年龄小于零!");
        }
        if(age>150){
          throw new Runti("年龄大于150!");
        }
        this.age = age;
    }
}

测试类:

public class Testmain {
    public static void main(String[] args) throws Age_0Exception {
        ZidingyiClasee z = new ZidingyiClasee();
        z.setAge(10);
        z.setAge(-1);//编译时异常
        z.setAge(151);//运行时异常
    }
}

运行结果:
请添加图片描述

请添加图片描述

标签:Java,自定义,Age,0Exception,ParseException,异常,public
来源: https://blog.csdn.net/sjjsaaaa/article/details/119111298