Java exception introduction and specific code of the architecture
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!

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

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

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 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.

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.
