How to handle exception types in Java
1. Description of exceptions
An unexpected event occurs when a program is running, which prevents the program from executing normally as expected by the programmer. This is an exception. When an exception occurs, the program is left to fend for itself and exits immediately. In Java, that is, errors that occur during Java compilation or operation or during operation.
Java provides a better solution: exception handling mechanism.
The exception handling mechanism allows the program to handle exceptions in a targeted manner according to the preset exception handling logic of the code when an exception occurs, so that the program can return to normal and continue execution as much as possible, while maintaining the clarity of the code. .
Exceptions in Java can be caused when statements in a function are executed, or they can be thrown manually by programmers through the throw statement. As long as an exception occurs in a Java program, a The exception object of the corresponding type is used to encapsulate the exception, and the JRE will try to find an exception handler to handle the exception.
Exception refers to an abnormal situation that occurs during runtime.
Abnormal situations are described and objects encapsulated in the form of classes in java.
A class that describes abnormal situations becomes an exception class.
Separate normal code and problem handling code to improve readability.
In fact, exceptions are Java encapsulating problems into objects through object-oriented thinking, and using exception classes to describe them.
2. Exception system
Two major categories:
hrowable: exceptions that can be thrown, whether it is error Or exception, it should be thrown when a problem occurs, so that the caller can know and handle it.
The characteristic of this system is that Throwable and all its subclasses are throwable.
What exactly does throwability mean? How to reflect throwability?
is reflected by two keywords.
throws throw All classes and objects that can be operated by these two keywords are throwable.
Subcategory 1 Generally unprocessable. ————Error
Characteristics: It is a serious problem thrown by jvm. When this kind of problem occurs, it is generally not dealt with in a targeted manner, and the program is directly modified.
Subclass 2) can handle it. ——Exception, the problem is thrown to the caller, whoever throws it to whom.
Features: The suffix names of subclasses are all suffixed with the name of their parent class, which is very readable!
Example: For example, customize an exception with a negative index and encapsulate it into an object using object-oriented thinking.
Note: If a class is called an exception class, it must inherit the exception class. Because only subclasses of the exception system are throwable.
class FuShuIndex extends Exception{ //构造函数 和类名一样 FuShuIndex(){ } //定义一个带参数的构造函数 FuShuIndex(String msg){ //调用Exception中的带参数异常函数 super(msg); } } 主函数 throws FuShuIndex:{ int[] arr = new int[3]; method(arr,-7); } public static int method(int[] arr,int index) throws arrIndexexception { if (index<0){ throw new arrIndexexception("数组的角标不能为负数"); } return arr[index]; }
3. Exception classification:
Exceptions detected during compilation are also Exception and its subclasses, except for the special subclass RuntimeException, which is compiled without processing fail!
Once this kind of problem occurs, we hope to detect it at compile time so that this kind of problem can be dealt with accordingly, so that such problems can be dealt with in a targeted manner.
Undetected exceptions during compilation (runtime exceptions): RuntimeException and its subclasses
can be processed or not, and the compilation can pass , it will be detected at runtime!
The occurrence of this kind of problem is that the function cannot be continued and the operation cannot be run. It is mostly caused by the call or the change of the internal state. This kind of problem is generally not dealt with, and is directly compiled and passed. At runtime, the program is forced to stop by the caller, allowing the caller to correct the code.
The difference between throws and throw:
throws is used on functions ————Statement
throw is used within a function, and multiple ones can be thrown, separated by commas. ——Throws
throws throws an exception class, and multiple exceptions can be thrown.
throw throws an exception object.
4. Capture form of exception handling
This is a way to handle exceptions in a targeted manner.
Format:
try{ //需要被检测异常的代码 } catch(异常类 变量)//该变量用于接收发生的异常对象{ //处理异常代码 } finally{ //一定会被执行的代码 }
Example
class FuShuIndex extends Exception{ //构造函数 和类名一样 FuShuIndex(){ } //定义一个带参数的构造函数 FuShuIndex(String msg){ //调用Exception中的带参数异常函数 super(msg); } }
Main function: No need for throws, let’s catch the exception ourselves
{ int[] arr = new int[3]; try{ method(arr,-7); }catch(arrIndexexception a){ a.printStackTrace();//jvm默认的异常处理机制就是调用异常对象的这个方法。 System.out.println("数组的角标异常!!!");//自定义捕获后打印的信息 System.out.println(a.toString());//打印该异常对象的信息 System.out.println(a.getMessage());//获取我们自定义抛出所定义的信息 } } public static int method(int[] arr,int index) throws arrIndexexception { if (index<0){ throw new arrIndexexception("数组的角标不能为负数"); } return arr[index]; }
One try corresponds to multiple catches:
In the case of multiple catches, the catch of the parent class should be placed at the bottom, otherwise the compilation will be empty.
5. Principles of exception handling
If an exception that needs to be detected is thrown inside a function, it must be declared in the function, or it must be caught with try catch within the function. , otherwise the compilation fails.
If the function that declares an exception is called, either try catch or throws, otherwise the compilation fails.
When to catch? When throws?
Function content can be solved by using catch.
If it cannot be solved, use throws to tell the caller, and the caller will solve it.
一个功能如果抛出了多个异常,那么调用时,必须有对应的多个catch来进行针对性处理。
内部有几个需要检测的异常,就抛几个异常,抛出几个就catch几个异常。
六、finally
通常用于关闭(释放)资源。必须要执行。除非jvm虚拟机挂了。
范例:出门玩,必须关门,所以将关门这个动作放在finally里面,必须执行。
凡是涉及到关闭连接等操作,要用finally代码块来释放资源。
try catch finally 代码块组合特点:
try catch finally:当有资源需要释放时,可以定义finally
try catch(多个):当没有资源需要释放时,可以不定义finally
try finally:异常处理不处理我不管,但是我得关闭资源,因为资源是我开的,得在内部关掉资源。
范例:
try{ //连接数据库 } //没有catch意思不处理异常,只单纯的捕获异常 finally{ //关闭连接 }
七、异常的应用
老师用电脑讲课范例:
电脑类:
public class Computer { private int state = 2; public void run() throws lanpingExcption,maoyanExcption{ if (state == 1){ throw new lanpingExcption("电脑蓝屏啦~"); }else if (state == 2){ throw new maoyanExcption("电脑冒烟啦~"); } System.out.println("电脑启动"); } public void chongqi(){ state = 0; System.out.println("重启电脑!"); } }
老师类:
public class Teacher { private String name; private Computer computer; Teacher(String name){ this.name = name; computer = new Computer(); } void teach() throws maoyanExcption{ try { computer.run(); System.out.println(this.name + "开始用电脑讲课了"); } catch (lanpingExcption l) { l.printStackTrace(); computer.chongqi(); teach();//重启后再次讲课 } catch (maoyanExcption m) { m.printStackTrace(); test(); throw m; } } public void test(){ System.out.println("大家自己练习去~"); } }
蓝屏异常类:
public class lanpingExcption extends Exception{ lanpingExcption (String msg){ super(msg); } }
冒烟异常类:
public class maoyanExcption extends Exception { maoyanExcption (String msg){ super(msg); } }
主函数:
public class Testmain { public static void main (String[] args){ Teacher teacher = new Teacher("丁老师"); try { teacher.teach(); } catch (maoyanExcption m) { //m.printStackTrace(); System.out.println("。。。。。"); } } }
八、异常的注意事项:
子类在覆盖父类方法时,父类的方法如果抛出了异常,那么子类的方法只能抛出父类的异常或者该异常的子类。
如果父类抛出多个异常,那么子类只能抛出父类异常的子集。
子类覆盖父类,只能抛出父类的异常或者子类。
如果父类的方法没有抛出异常,子类覆盖时绝对不能抛。
The above is the detailed content of How to handle exception types in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
