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
Java Application Performance Monitoring (APM) ToolsJava Application Performance Monitoring (APM) ToolsJul 24, 2025 am 03:37 AM

Common JavaAPM tools include NewRelic, DatadogAPM, AppDynamics, SkyWalking, Pinpoint and Prometheus Grafana Micrometer combinations; whether APM is required depends on system lag, complex microservice calls, performance details and optimization requirements; APM should consider deployment methods, learning costs, performance impact, cost and integration capabilities; when using them, you should pay attention to reasonable configuration, sampling rate, alarm rules, and analyze the root cause in combination with code.

Building Reactive Java Applications with RxJavaBuilding Reactive Java Applications with RxJavaJul 24, 2025 am 03:35 AM

1.RxJava is a responsive framework based on observer pattern and functional programming, suitable for handling asynchronous and non-blocking tasks. 2. Core types include Observable, Flowable, Single, etc., which are used to represent different forms of data flow. 3. Data conversion and combination are performed through operators such as map, filter, and flatMap to simplify complex logic. 4. Use Schedulers.io(), Schedulers.computation(), AndroidSchedulers.mainThread() and other schedulers to control thread switching. 5. Specify the data flow start thread through subscribeOn, obse

Implementing a Thread-Safe Singleton in JavaImplementing a Thread-Safe Singleton in JavaJul 24, 2025 am 03:35 AM

When using double check lock to implement lazy loading singletons, the volatile keyword is required to ensure thread visibility and prevent instruction re-arrangement; 2. It is recommended to use static internal classes (BillPugh scheme) to implement thread-safe lazy loading singletons, because the JVM ensures thread safety and no synchronization overhead; 3. If you do not need lazy loading, you can use static constants to implement simple and efficient singletons; 4. When serialization is involved, enumeration method should be used, because it can naturally prevent multiple instance problems caused by reflection and serialization; in summary, general scenarios prefer static internal classes, and serialized scenarios to select enumerations. Both have the advantages of thread safety, high performance and concise code.

Comparing Java, Kotlin, and Scala for Backend DevelopmentComparing Java, Kotlin, and Scala for Backend DevelopmentJul 24, 2025 am 03:33 AM

Kotlinoffersthebestbalanceofbrevityandreadability,Javaisverbosebutpredictable,andScalaisexpressivebutcomplex.2.Scalaexcelsinfunctionalprogrammingwithfullsupportforimmutabilityandadvancedconstructs,KotlinprovidespracticalfunctionalfeatureswithinanOOPf

Managing Dependencies in a Large-Scale Java ProjectManaging Dependencies in a Large-Scale Java ProjectJul 24, 2025 am 03:27 AM

UseMavenorGradleconsistentlywithcentralizedversionmanagementandBOMsforcompatibility.2.Inspectandexcludetransitivedependenciestopreventconflictsandvulnerabilities.3.EnforceversionconsistencyusingtoolslikeMavenEnforcerPluginandautomateupdateswithDepend

Mastering Java 8 Streams and LambdasMastering Java 8 Streams and LambdasJul 24, 2025 am 03:26 AM

The two core features of Java8 are Lambda expressions and StreamsAPI, which make the code more concise and support functional programming. 1. Lambda expressions are used to simplify the implementation of functional interfaces. The syntax is (parameters)->expression or (parameters)->{statements;}, for example (a,b)->a.getAge()-b.getAge() instead of anonymous internal classes; references such as System.out::println can further simplify the code. 2.StreamsAPI provides a declarative data processing pipeline, the basic process is: create Strea

Java Security Tokenization and EncryptionJava Security Tokenization and EncryptionJul 24, 2025 am 03:24 AM

SecurityToken is used in Java applications for authentication and authorization, encapsulating user information through Tokenization to achieve stateless authentication. 1. Use the jjwt library to generate JWT, select the HS256 or RS256 signature algorithm and set the expiration time; 2. Token is used for authentication, Encryption is used for data protection, sensitive data should be encrypted using AES or RSA, and passwords should be stored with hash salt; 3. Security precautions include avoiding none signatures, setting the expiration time of tokens, using HTTPS and HttpOnlyCookies to store tokens; 4. In actual development, it is recommended to combine SpringSecurity and

The role of `var` for Local-Variable Type Inference in JavaThe role of `var` for Local-Variable Type Inference in JavaJul 24, 2025 am 03:23 AM

var was introduced in Java 10 for local variable type inference, to determine the type during compilation, and maintain static type safety; 2. It can only be used for local variables in methods with initialized expressions, and cannot be used for fields, parameters or return types; 3. Non-initialization, null initialization and lambda expression initialization are prohibited; 4. It is recommended to use them when the type is obvious to improve simplicity and avoid scenarios that reduce readability. For example, types should be explicitly declared when complex methods are called.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.