异常的概述与使用

    xiaoxiao2025-02-17  14

    平常我们开发当中经常为遇到一些错误,而阻止Java程序的运行,我们就成为异常。 例如我们在实际开发当中常见的异常:

    NumberFormatExcepiton 字符串转换为数字异常NullException 空指针异常ArrayIndexOutOfBountsException 数组角标越界异常ClassNotFountException 未找到类异常SQLException 数据库异常

    等等

    对于这些异常Exception 是需要我们程序员进行捕获处理我标明抛出相关的处理。

    捕捉异常方式

    使用 try-catch 异常捕获结构 由三部分组成,try - catch - finally。需要强调下 finally,他是Exception 处理最后执行的部分, 不论 try 语句中的代码块怎么退出都将执行 finally 语句!

    使用 throws 抛出异常 throws 是用来指定该方法可能抛出的异常,通常应用在声明方法时。如以下简单的实例:

    public class MyClass { public static void main(String args[]){ System.out.println("Hello World !"); selectMethod("select"); } public static void selectMethod(String data) throws NumberFormatException{ int number = Integer.parseInt(data); System.out.println("得出的数字结果值:"+number); } }

    编译得出以下错误异常信息:

    Exception in thread "main" java.lang.NumberFormatException: For input string: "select" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at com.example.MyClass.selectMethod(MyClass.java:11) at com.example.MyClass.main(MyClass.java:6) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) Hello World ! Process finished with exit code 1

    但是这样依然是没有达到我们的要求,我们是需要在程序出现已知或未知的错误异常信息之后依然能够执行后面的方法,所以我们的结合 try-catch 语句块来进行捕获处理

    public class MyClass { public static void main(String args[]) { try { selectMethod("select"); } catch (Exception ex) { } System.out.println("Hello World !"); }

    这样的话编译就能通过虽然说不符合相关的结果要求!但是模拟的情况我们是实现了!

    3。 使用自定义异常

    1、创建自定义异常类 2、在相关的方法中通过 throw 抛出异常的对象。 3、使用 try - catch 语句进行相关异常的捕获和处理

    package com.example; public class MyClass { public static void main(String args[]) { try { selectMethod("select"); } catch (Exception ex) { } //----------------自定义异常---------- try { testMethod(4); } catch (ResultException e) { e.printStackTrace(); e.getErrorCode(); System.out.println(e.getErrorCode()); } System.out.println("Hello World !"); } /** * throws 的使用 * @param data */ public static void selectMethod(String data) throws NumberFormatException{ int number = Integer.parseInt(data); System.out.println("得出的数字结果值:" + number); } /** * 自定义异常的使用 * @param data * @throws ResultException */ public static void testMethod(int data) throws ResultException{ if (data < 10){ throw new ResultException("404","错误异常信息!!!!"); } } }

    对于异常的处理和捕获,有利于我们管理我们代码的阅读性,和规范性,安全性! 所以我们必须的灵活的使用异常的常用设计,以此为我们以后重构代码做出简单、规范的梳理!

    转载请注明原文地址: https://ju.6miu.com/read-1296523.html
    最新回复(0)