This article mainly shares the introduction and architecture of Java exceptions, which has certain reference value. Interested friends can refer to it
Introduction to Java exceptions
Java exceptions are a consistent mechanism provided by Java to identify and respond to errors.
The Java exception mechanism can separate the exception handling code in the program from the normal business code, ensuring that the program code is more elegant and improving the robustness of the program. When exceptions are used effectively, exceptions can clearly answer the three questions what, where, why: the exception type answers "what" was thrown, and the exception stack trace answers "where" it was thrown. Out, the exception message answers "why" it is thrown.
Several keywords used in the Java exception mechanism: try, catch, finally, throw, throws.
•try -- used for monitoring. Place the code to be monitored (the code that may throw an exception) within the try statement block. When an exception occurs within the try statement block, the exception will be thrown.
•catch -- used to catch exceptions. catch is used to catch exceptions that occur in the try statement block.
• finally -- The finally statement block will always be executed. It is mainly used to recycle physical resources (such as database connections, network connections, and disk files) opened in try blocks. Only the finally block, after execution is completed, will come back to execute the return or throw statement in the try or catch block. If a statement such as return or throw is used in the finally block, it will not jump back to execution and stop directly.
• throw -- used to throw exceptions.
• throws -- used in method signatures to declare exceptions that may be thrown by the method.
The following is a brief understanding of these keywords through several examples.
Example 1: Understand the basic usage of try and catch
public class Demo1 { public static void main(String[] args) { try { int i = 10/0; System.out.println("i="+i); } catch (ArithmeticException e) { System.out.println("Caught Exception"); System.out.println("e.getMessage(): " + e.getMessage()); System.out.println("e.toString(): " + e.toString()); System.out.println("e.printStackTrace():"); e.printStackTrace(); } } }
Running results:
Caught Exception
e.getMessage(): / by zero
e.toString(): java.lang.ArithmeticException: / by zero
e.printStackTrace():
java .lang.ArithmeticException: / by zero
at Demo1.main(Demo1.java:6)
Result description: There is an operation of dividing by 0 in the try statement block. The operation will throw java.lang.ArithmeticException. Catch the exception through catch.
Observing the results, we found that System.out.println("i="+i) was not executed. This shows that after an exception occurs in the try statement block, the remaining content in the try statement block will no longer be executed.
Example 2: Understand the basic usage of finally
Based on "Example 1", we add the finally statement.
public class Demo2 { public static void main(String[] args) { try { int i = 10/0; System.out.println("i="+i); } catch (ArithmeticException e) { System.out.println("Caught Exception"); System.out.println("e.getMessage(): " + e.getMessage()); System.out.println("e.toString(): " + e.toString()); System.out.println("e.printStackTrace():"); e.printStackTrace(); } finally { System.out.println("run finally"); } } }
Run result:
Caught Exception
e.getMessage(): / by zero
e.toString() : java.lang.ArithmeticException: / by zero
e.printStackTrace():
java.lang.ArithmeticException: / by zero
at Demo2.main(Demo2.java:6)
run finally
Result description: The finally statement block is finally executed.
Example 3: Understand the basic usage of throws and throw
throws is used to declare thrown exceptions, and throw is used to throw exceptions.
class MyException extends Exception { public MyException() {} public MyException(String msg) { super(msg); } } public class Demo3 { public static void main(String[] args) { try { test(); } catch (MyException e) { System.out.println("Catch My Exception"); e.printStackTrace(); } } public static void test() throws MyException{ try { int i = 10/0; System.out.println("i="+i); } catch (ArithmeticException e) { throw new MyException("This is MyException"); } } }
Run result:
Catch My Exception
MyException: This is MyException
at Demo3.test( Demo3.java:24)
at Demo3.main(Demo3.java:13)
Result description:
MyException is inherited from Exception Subclass. An ArithmeticException exception (divisor is 0) is generated in the try statement block of test(), and the exception is captured in catch; then a MyException exception is thrown. The main() method captures the MyException thrown in test().
Java exception framework
Java exception architecture diagram
1. Throwable
Throwable is the super class of all errors or exceptions in the Java language.
Throwable contains two subclasses: Error and Exception. They are often used to indicate that something unusual has occurred.
Throwable contains a snapshot of the thread execution stack when its thread is created. It provides interfaces such as printStackTrace() to obtain stack trace data and other information.
2. Exception
Exception and its subclasses are a form of Throwable, which points out reasonable The conditions that the application wants to capture.
3. RuntimeException
RuntimeException is the superclass of exceptions that may be thrown during normal operation of the Java virtual machine.
The compiler will not check RuntimeException. For example, when the divisor is zero, an ArithmeticException is thrown. RuntimeException is the superclass of ArithmeticException. When the code divides by zero, it can still be compiled if it neither "throws an ArithmeticException through the throws declaration" nor "handles the exception through try...catch...". This is what we mean by "the compiler does not check for RuntimeException"!
If the code will generate a RuntimeException, you need to modify the code to avoid it. For example, if division by zero occurs, you need to avoid this through code!
4. Error
Like Exception, Error is also a subclass of Throwable. It is used to indicate serious problems that reasonable applications should not attempt to catch; most such errors are exceptional conditions.
Like RuntimeException, the compiler will not check for Error.
Java divides throwable structures into three types: Checked Exception, RuntimeException and Error.
(01) Runtime exception
Definition: RuntimeException and its subclasses are called runtime exceptions.
Features: Java compiler will not check it. In other words, when this kind of exception may occur in the program, if it is neither thrown through the throws statement nor caught with a try-catch statement, it will still be compiled. For example, ArithmeticException generated when the divisor is zero, IndexOutOfBoundsException generated when the array exceeds the bounds, ConcurrentModificationException generated by the fail-fail mechanism, etc., are all runtime exceptions.
Although the Java compiler does not check runtime exceptions, we can also declare a throw through throws, or catch it through try-catch.
If a runtime exception occurs, it needs to be avoided by modifying the code. For example, if division by zero occurs, you need to avoid this through code!
(02) Checked exception
Definition: Exception class itself, and other subclasses of Exception subclasses except "runtime exception" It is a checked exception.
Features: Java compiler will check it. Such exceptions must either be declared and thrown through throws, or caught and processed through try-catch, otherwise they cannot pass compilation. For example, CloneNotSupportedException is a checked exception. When an object is cloned through the clone() interface, and the class corresponding to the object does not implement the Cloneable interface, a CloneNotSupportedException exception will be thrown.
Checked exceptions are usually recoverable.
(03) Error
Definition: Error class and its subclasses.
Features: Like runtime exceptions, the compiler will not check for errors.
When resources are insufficient, constraints fail, or other conditions occur that prevent the program from continuing to run, an error occurs. The program itself cannot fix these errors. For example, VirtualMachineError is an error.
According to Java convention, we should not implement any new Error subclasses!
For the above three structures, which one should we use when throwing an exception or error? The advice given in "Effective Java" is to use checked exceptions for recoverable conditions and runtime exceptions for program errors.
The above is the detailed content of Java exception introduction and specific code of the architecture. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
