search
HomeJavajavaTutorialDetailed introduction to Java exception handling

This article brings you a detailed introduction to Java exception handling. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Let’s take a look at an example and some knowledge points about Java exception handling (Exception Handling).

Detailed introduction to Java exception handling

Look at the program below. The method pleaseThrow accepts an instance of Exception and simply throws the instance. Then when calling this method, I passed in an instance of SQLException. Because the call to pleaseThrow is wrapped in a try catch block,

Question: Can the SQLException thrown by the pleaseThrow method be successfully caught?

public class ExceptionForQuiz<t> {

      private void pleaseThrow(final Exception t) throws T {

             throw (T) t;

      }

     public static void main(final String[] args) {

          try {

               new ExceptionForQuiz<runtimeexception>().pleaseThrow(new SQLException());

          }

         catch( final SQLException ex){

              System.out.println("Jerry print");

              ex.printStackTrace();

        }

}

}</runtimeexception></t>

Detailed introduction to Java exception handling

Answer: The above code has a grammatical error and cannot be compiled!

Let’s analyze it step by step.

The Java class ExceptionForQuiz uses a generic syntax. T extends Exception means that when this generic class is instantiated, the type parameter T passed in must be Exception and its subclasses.

When I instantiate the class ExceptionForQuiz, the type parameter passed in is RuntimeException.

RuntimeException is an Unchecked exception in Java. Even if a RuntimeException may be thrown when a method is running, developers do not need to explicitly declare it in code before the method.

Look at the comments of JDK RuntimeException and it is very clear: Unchecked exceptions do NOT need to be declared in a method or constructor's clause if they can be thrown by the execution of the method or constructor.

The author Frank Yellin must be a great guy.

Detailed introduction to Java exception handling

Because generics are a concept introduced in Java 1.5, there is a concept of type erasure for generics, that is, generics The information only exists in the code compilation phase. In the compiled code, the information related to generics will be erased. For example, if the type parameter part in the previous generic class does not specify an upper limit, written like this , it will be translated into an ordinary Object type. If an upper limit is specified such as , the type parameter is replaced by the type upper limit.

For the sake of simplicity, we first remove the try catch block in the code.

Detailed introduction to Java exception handling

The following is the code after decompilation from ExceptionForQuiz.class:

Detailed introduction to Java exception handling

We can observe from the above figure that the generic parameter RuntimeException of methods pleaseThrow and RayExceptionForQuiz has been erased. The exception type that can be thrown by the pleaseThrow method has been erased and becomes Exception.

Use javap to observe the bytecode generated by compilation, and you can also find the fact that the type parameter RuntimeException has been erased:

Look at the second red highlighted area: Exceptions: throw java.lang. Exception

Detailed introduction to Java exception handling

Now let’s see what error message the compiler will report: Unreachable catch block for SQLException. This exception is never thrown from the try statement body .

Detailed introduction to Java exception handling

This error message is reasonable based on the fact that exception type is erased, since the declaration of the pleaseThrow method can now only throw exceptions of type exception, so the catch on line 14 can never receive an exception of type SQLException, so the compiler throws an error.

How to eliminate this compiler error? Just change the SQLException on line 14 to RuntimeException.

But in this case, although the syntax error is eliminated, the SQLException thrown by the pleaseThrow method cannot be caught, and a runtime error will be reported:

Detailed introduction to Java exception handling

How to use the catch statement to catch the SQLException thrown by pleaseThrow? Change RuntimeException on line 14 to the superclass of all exceptions: Exception.

Execute again, this time there is neither syntax error nor runtime error: SQLException has been successfully caught by the catch statement on line 14.

Detailed introduction to Java exception handling

The above is the detailed content of Detailed introduction to Java exception handling. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)