


Completely master the principles and applications of Java exception handling mechanism
This article brings you relevant knowledge about java, which mainly introduces the principles and application-related issues of the exception handling mechanism, including Exception and Error, trycatch syntax, and trycatch execution order Wait, I hope it helps everyone.
Recommended study: "java Learning Tutorial"
1. Introduction to Java exceptions
Everyone may be interested in trycatch They are no strangers to it, and they are all very proficient in using it.
When an error occurs during the running of the program, an exception will be thrown. It is better to throw an exception than to terminate the program.
You can also perform a trycatch operation when it is known that an error is about to occur, and perform certain special operations when an exception occurs.
1, Exception and Error
Exception and Error both inherit from the Throwable class. In Java, only instances of the Throwable type can be thrown or caught. It is The basic component types of exception handling mechanisms.
Exception is a predictable abnormal situation, which can be obtained and processed outside the business.
Error is an unpredictable exception. When an error occurs, it will directly cause the JVM to be unable to handle it.
Exception is divided into checked exceptions and non-checked exceptions.
Checked exceptions must be caught using try catch when writing code (for example: IOException exception).
With non-checked exceptions, the compiler will not find out whether this will occur once, such as a null pointer exception. This kind of exception can be avoided through specification during code writing or use. For example, the findbugs function of sts can detect null pointer exceptions in the code.
2. What is the difference between NoClassDefFoundError and ClassNotFoundException?
NoClassDefFoundError is an error thrown by the JVM when it cannot find the corresponding class when loading a class through classpath.
ClassNotFoundException: If this exception may occur during compilation, it must be thrown during compilation.
NoClassDefFoundError occurrence scenarios:
- The class or jar that the class depends on does not exist
- The class file exists, but in a different domain. In short, Just can’t find the
ClassNotFoundException scenario:
- When calling the forName method of class, the specified class cannot be found
- findSystemClass in ClassLoader () method, the specified class cannot be found
public static void main(String[] args) { try { Class.forName("test"); } catch (ClassNotFoundException e) { e.printStackTrace(); }}
2. trycatch syntax
1. try statement
try statement is used Braces enclose a section of code that may throw one or more exceptions.
2. Catch statement
The parameters of the catch statement are similar to the declaration of a method, including an exception type and an exception object. The exception type must be a subclass of the Throwable class, which specifies the exception type processed by the catch statement. The exception object is generated and captured by the runtime system in the code block specified by try. The curly braces contain the processing of the object, where Object methods can be called.
There can be multiple catch statements to handle different types of exceptions respectively. The Java runtime system detects the exception type handled by each catch statement from top to bottom until a catch statement with a matching type is found. Here, type matching means that the exception type handled by catch is exactly the same as the type of the generated exception object or its parent class. Therefore, the order of catch statements should be from special to general.
3. Finally statement
Regardless of whether an exception is thrown in the try, the code in the finally statement will be executed. The most important function of the finally statement block should be to release Resources applied for.
4. Throws statement
throws always appears after the function header to indicate exceptions that may be thrown by the method.
5. The throw statement
is similar to throws, but the location is different. throw is placed in the catch module. The program will terminate immediately after the throw is executed. The code after throw No longer executed, except finally.
6. Throwing exceptions
public void test() throws Exception{ throw new Exception();};
7. Catching exceptions
try{ //代码区}catch(Exception e){ log.error("error: {}", e);}finally{ //最后必须执行的部分}
3. Trycatch execution sequence
Start execution from the first line of code in try. When the code that causes an exception is executed, the JVM will create an exception object.
Determine whether catch can capture the exception object created by jvm.
If caught, jump to the catch code block without ending the program and continue with the code logic in catch;
If it cannot be caught, print the exception information directly and end the program.
If there is no exception in try, the code in try will be executed, skip the catch, and enter the finally code block.
4. Exception handling principles
If an exception that needs to be detected is thrown in a method, it must be declared in the method, otherwise it must be caught with try-catch in the method, otherwise the compilation will fail.
If the function declaring an exception is called, either try-catch or throws, otherwise the compilation fails.
When to catch and when to throw? The functional content can be solved, but it cannot be solved by using catch. Use throws to tell the caller that there is a caller to solve it.
If a function throws multiple exceptions, there must be multiple corresponding catches for targeted processing when calling.
Recommended study: "java tutorial"
The above is the detailed content of Completely master the principles and applications of Java exception handling mechanism. 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

AI Hentai Generator
Generate AI Hentai for free.

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



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

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

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.

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
