Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of Java exception handling mechanism

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces what Java exception handling mechanism is used for, and has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

1. Exception Overview and Exception Architecture 1.1 Exception Overview

Exception: In Java, an abnormal condition that occurs during program execution is called an exception. (Syntax errors and logic errors during development are not exceptions)

Exceptions that occur during Java program execution can be divided into two categories:

Error: A serious problem that the Java Virtual Machine cannot solve. For example: JVM system internal errors, resource exhaustion and other serious situations. Examples: StackOverflowError and OOM. Generally not written targeted

The code is processed.

Exception: Other general problems caused by programming errors or accidental external factors that can cause

Processing with targeted code.

For example:

null pointer access attempting to read a file that does not exist network connection interrupt array pointer out of bounds

1.2 Run-time and compile-time exceptions

For these errors, there are generally two solutions: one is to encounter errors on the termination of the program

operation. Another way is for programmers to take errors into account when writing programs.

Detection, error message indication, and error handling.

Errors are ideally caught during compilation, but some errors occur only at runtime.

For example: divisor is 0, array subscript is out of bounds, etc.

Categories: Compile-time exceptions and run-time exceptions

1. runtime exception

An exception that the compiler does not require mandatory handling. Generally refers to programming logic errors, is the program

Employees should actively avoid anomalies that occur. java.lang.RuntimeException class and its children

Classes are runtime exceptions.

For this type of exception, you can leave it unhandled because it is so common that if you handle it fully, you may have a problem with it.

The readability and efficiency of the program.

2. compile-time exception

An exception that the compiler requires must be handled. That is, when the program is running, it is caused by external factors.

General abnormalities. The compiler requires Java programs to catch or declare all compile-time exceptions.

This type of exception, if not handled by the program, may bring unexpected results.

1.3 exception architecture

2. common abnormal

java.lang.RuntimeException

ClassCastExceptionArrayIndexOutOfBoundsExceptionNullPointerExceptionArithmeticExceptionNumberFormatExceptionInputMismatchException

java.io.IOExeption

FileNotFoundExceptionEOFException

java.lang.ClassNotFoundException

java.lang.InterruptedException

java.io.FileNotFoundException

java.sql.SQLException

1. ArrayIndexOutOfBoundsExceptionpublic class IndexOutExp { public static void main(String[] args) { String friends[] = { "lisa", "bily", "kessy" }; for (int i = 0; i

< 5; i++) { System.out.println(friends[i]); // friends[4]? } System.out.println("\nthis is the end"); }} 运行结果:数组越界异常

2.NullPointerExceptionpublic class NullRef{ int i = 1; public static void main(String[] args){ NullRef t = new NullRef(); t = null; System.out.println(t.i); } }

Run result: null pointer exception

3.ArithmeticExceptionpublic class DivideZero{ int x; public static void main(String[] args){ int y; DivideZero c=new DivideZero(); y=3/c.x; System.out.println("program ends ok!"); }}

运行结果:除零异常

4.ClassCastExceptionpublic class Order{ public static void main(String[] args){ Object obj = new Date(); Order order; order = (Order) obj; System.out.println(order); }}

运行结果:类转换异常

3.异常处理机制3.1异常的抛出与捕获

Java提供的是异常处理的抓抛模型

抛出异常

Java程序的执行过程中如出现异常,会生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。

异常对象的生成

由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,如果在当前代码中没有找到相应的处理程序,就会在后台自动创建一个对应异常类的实例对象并抛出--自动抛出由开发人员手动创建:Exception exception = new ClassCastException();--创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样

异常的抛出机制:

捕获异常

如果一个方法内抛出异常,该异常对象会被抛给调用者方法中处理。如果异常没有在调用者方法中处理,它继续被抛给这个调用方法的上层方法。这个过程将一直继续下去,直到异常被处理。这一过程称为捕获(catch)异常。

如果一个异常回到main()方法,并且main()也不处理,则程序运

行终止。

程序员通常只能处理Exception,而对Error无能为力。

3.2异常处理机制:try-catch-finally

异常处理是通过try-catch-finally语句实现的

try{...... //可能产生异常的代码}catch( ExceptionName1 e ){...... //当产生ExceptionName1型异常时的处置措施}catch( ExceptionName2 e ){...... //当产生ExceptionName2型异常时的处置措施}[ finally{...... //无论是否发生异常,都无条件执行的语句} ]

try

捕获异常的第一步是用try{…}语句块选定捕获异常的范围,将可能出现

异常的代码放在try语句块中。

catch (Exceptiontype e)

在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随

一个或多个catch语句,用于处理可能产生的不同类型的异常对象。

finally

捕获异常的最后一步是通过finally语句为异常处理提供一个

统一的出口,不论在try代码块中是否发生了异常事件,catch语句是否执

行,catch语句是否有异常,catch语句中是否有return,finally块中的语句都会被执行。

捕获异常的有关信息:

与其它对象一样,可以访问一个异常对象的成员变量或调用它的

方法。

getMessage() 获取异常信息,返回字符串printStackTrace() 获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。

举例:指针越界

public class IndexOutExp{ public static void main(String[] args){ String friends[] = { "lisa", "bily", "kessy" }; try{ for (int i = 0; i < 5; i++) { System.out.println(friends[i]); } }catch (ArrayIndexOutOfBoundsException e){ System.out.println("index err"); } System.out.println("\nthis is the end"); }}//程序IndexOutExp.java运行结果:java IndexOutExplisabilykessyindex errthis is the end5.用户自定义异常类

一般地,用户自定义异常类都是RuntimeException的子类。

自定义异常类通常需要编写几个重载的构造器。 l 自定义异常需要提供serialVersionUID自定义的异常通过throw抛出。自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。

用户自定义异常类MyException,用于描述数据取值范围错误信息。用户

自己的异常类必须继承现有的异常类

public class Test { private static String userName = "admin"; private static String password = "123456"; public static void main(String[] args) { login("admin", "123456"); } public static void login(String userName, String password) { if (!Test.userName.equals(userName)) { // TODO 处理用户名错误 } if (!Test.password.equals(password)) { // TODO 处理密码错误 } System.out.println("登陆成功"); } }

此时我们在处理用户名密码错误的时候可能就需要抛出两种异常. 我们可以基于已有的异常类进行扩展(继承), 创建和我们业务相关的异常类

class UserError extends Exception { public UserError(String message) { super(message); } } class PasswordError extends Exception { public PasswordError(String message) { super(message); } }

此时我们的 login 代码可以改成

public static void main(String[] args) { try { login("admin", "123456"); } catch (UserError userError) { userError.printStackTrace(); } catch (PasswordError passwordError) { passwordError.printStackTrace(); } } public static void login(String userName, String password) throws UserError, PasswordError { if (!Test.userName.equals(userName)) { throw new UserError("用户名错误"); } if (!Test.password.equals(password)) { throw new PasswordError("密码错误"); } System.out.println("登陆成功"); }

注意事项:

自定义异常通常会继承自 Exception 或者 RuntimeException

继承自 Exception 的异常默认是受查异常

继承自 RuntimeException 的异常默认是非受查异常

6.异常处理5个关键字

感谢你能够认真阅读完这篇文章,希望小编分享的"Java异常处理机制有什么用"这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report