Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Java throws an exception in a method

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the relevant knowledge of how Java throws an exception in the method, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this Java article on how to throw an exception in the method. Let's take a look.

Overview of exception mechanism

The exception mechanism refers to how the program handles when an error occurs. Specifically, the exception mechanism provides a safe channel for the program to exit. When an error occurs, the process of the program execution changes and the control of the program is transferred to the exception handler.

The flow of exception handling

When an exception is thrown in the program, the program jumps out of the code that caused the exception in the program, and the java virtual machine detects and looks for the catch block that matches the try keyword to handle the exception. If found, it hands over the control to the code in the catch block, and then continues to execute the program, and the code that occurs the exception in the try block will not be reexecuted. If the catch block that handles the exception is not found, the current thread that encountered the exception is aborted after all the finally block code is executed and the uncaughtException method of the ThreadGroup to which the current thread belongs is called.

Abnormal structure

The inheritance structure of the exception: Throwable is the base class, and Error and Exception inherit Throwable,RuntimeException and IOException inherit Exception. Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other anomalies become checked exceptions (checked).

Error exception

Error indicates that there is a very serious and unrecoverable error while the program is running, in which case the application can only be aborted, such as an error in the JAVA virtual machine. Error is a unchecked Exception, and the compiler does not check whether Error is handled or not, and there is no need to catch exceptions of type Error in the program. In general, an exception of type Error should not be thrown in a program.

RuntimeException exception

Exception exceptions include RuntimeException exceptions and other non-RuntimeException exceptions. RuntimeException is a Unchecked Exception, which means that the compiler does not check whether the program has handled RuntimeException, does not have to catch exceptions of type RuntimException in the program, and does not have to throw the RuntimeException class in the method body declaration. When RuntimeException occurs, it indicates that there is a programming error in the program, so you should find the error to modify the program instead of capturing the RuntimeException.

Checked Exception exception

Checked Exception exception, which is also the most frequently used Exception in programming, all exceptions that inherit from Exception and are not RuntimeException are checked Exception, IOException and ClassNotFoundException in the figure above. The JAVA language states that checked Exception must be processed, and the compiler checks it, either declaring that checked Exception is thrown in the method body, or using catch statements to capture checked Exception for processing, otherwise it cannot be compiled.

Throw an exception when declaring a method

Syntax: throws

Why throw an exception in a declaration method?

Whether the method throws an exception is as important as the type of value that the method returns. Assuming that a method throws an exception without declaring that the method will throw an exception, the client programmer can call the method without writing code to handle the exception. Then, once an exception occurs, there is no appropriate exception controller to resolve the exception.

Why does the exception thrown have to be checked? RuntimeException and Error can be generated in any code, they do not need to be thrown by the programmer, once an error occurs, then the corresponding exception will be automatically thrown. When you encounter Error, programmers are generally powerless; when you encounter RuntimeException, there must be logic errors in the program and you have to modify the program; only checked exceptions are of concern to programmers, and the program should and should only throw or handle checked exceptions. The check exception is thrown by the programmer, which is divided into two cases: the client programmer calls the library function that throws the exception; the client programmer uses the throw statement to throw the exception.

Note: a subclass method that overrides a method of the parent class cannot throw more exceptions than the method of the parent class, so sometimes the method of the parent class will be declared to throw an exception, but the actual code that implements the method will not throw an exception. The purpose of this is to facilitate the subclass method to override the parent class method can throw an exception.

How to throw an exception in a method

Syntax: what exception does throw throw?

For an exception object, the really useful information is the object type of the exception, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, then the class name is * useful information. Therefore, when choosing what exception to throw, the most important thing is to select the class name of the exception that clearly describes the exception.

There are usually two types of constructors for exception objects: one is a constructor with no arguments, and the other is a constructor with a string that will be used as an additional description of the exception object in addition to the type name.

Why create your own exception?

When none of the built-in exceptions in Java can clearly describe the exception, you need to create your own exceptions. It is important to note that what is useful is the type name information, so don't spend energy on the design of exception classes.

The difference between throw and throws

Public class TestThrow {public static void main (String [] args) {try {/ / calls a method with a throws declaration, and must explicitly catch the exception / / otherwise, you must declare that throwChecked (- 3) is thrown again in the main method } catch (Exception e) {System.out.println (e.getMessage ());} / / call the method that throws the Runtime exception to either explicitly catch the exception or ignore the exception throwRuntime (3) } public static void throwChecked (int a) throws Exception {if (a > 0) {/ / throw an Exception exception / / the code must be in a try block or throw new Exception in a method with a throws declaration ("the value of an is greater than 0, does not meet the requirements") }} public static void throwRuntime (int a) {if (a > 0) {/ / throws a RuntimeException exception by itself, either explicitly catches the exception / / or completely ignores the exception, and hands the exception to the method caller to handle throw new RuntimeException ("the value of an is greater than 0, does not meet the requirements") }

Add: another way to write the throwChecked function is as follows:

Public static void throwChecked (int a) {if (a > 0) {/ / throw an Exception exception / / the code must be in a try block or in a method with a throws declaration try {throw new Exception ("the value of an is greater than 0, does not meet the requirements") } catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace ();}

Note: throwChecked does not need a try exception in the main function at this time.

Should an exception be thrown in the declaring method or caught in the method?

Handling principle: catch and handle exceptions that know how to handle, and pass exceptions that don't know how to handle

Use finally blocks to release resources

The finally keyword guarantees that statements in the finally will be executed no matter how the program leaves the try block. The finally block is entered in the following three cases:

(1) the code in the try block has been executed normally.

(2) throw an exception in the try block.

(3) execute return, break, continue in the try block.

So when you need a place to execute code that must be executed under any circumstances, you can put that code in a finally block. When your program uses external resources, such as database connections, files, etc., you must write the code that releases these resources into the finally block.

It is important to note that exceptions cannot be thrown in finally blocks. The JAVA exception handling mechanism ensures that the finally block must be executed before leaving the try block in any case, so when an exception occurs in the try block, the JAVA virtual machine first goes to the finally block to execute the code in the finally block, and then throws the exception after the execution of the finally block. If an exception is thrown in a finally block, the exception caught by the try block cannot be thrown, and the exception caught externally is the exception information in the finally block, while the real exception stack information that occurs in the try block is lost. Take a look at the following code:

Connection con = null; try {con = dataSource.getConnection ();. } catch (SQLException e) {. Throw e handle / throw the database exception to the caller after some processing} finally {try {con.close ();} catch (SQLException e) {e.printStackTrace ();... }}

After running the program, the caller gets the following information

Java.lang.NullPointerException at myPackage.MyClass.method1 (methodl.java:266)

Instead of the database exception we expected. This is because the con here is null, and NullPointerException is thrown in the finally statement, which can be avoided by adding a judgment in the finally block that whether con is null or not.

Missing exception

Take a look at the following code:

Public void method2 () {try {. Method1 (); / / method1 performed database operations} catch (SQLException e) {. Throw new MyException ("Database exception occurred:" + e.getMessage);}} public void method3 () {try {method2 ();} catch (MyException e) {e.printStackTrace (); … }}

In the method2 code above, the try block catches the database exception SQLException thrown by method1 and throws a new custom exception MyException. There is nothing wrong with this code, but take a look at the console output:

MyException: a database exception occurred: the object name 'MyTable' is invalid.

At MyClass.method2 (MyClass.java:232)

At MyClass.method3 (MyClass.java:255)

The information of the original exception SQLException is lost, and you can only see the stack of the MyException defined in the method2. However, the stack of the database exception that occurs in the method1 cannot be seen. How to debug it, you can only find the database operation statement line by line in the code line of the method1.

JDK developers are also aware of this. In JDK1.4.1, the Throwable class adds two constructors, public Throwable (Throwable cause) and public Throwable (String message,Throwable cause), and the original exception stack information passed in the constructor will be printed in the printStackTrace method. But programmers who are still using JDK1.3 can only print the original exception stack information on their own. The implementation process is also very simple, just add an original exception field to the custom exception class, pass the original exception in the constructor, then overload the printStackTrace method, first call the printStackTrace method of the original exception saved in the class, and then call the super.printStackTrace method to print out the original exception information. You can define the MyException class that appeared in the previous code as follows:

Import java.io.PrintStream

Import java.io.PrintWriter

Public class MyException extends Exception

{

Private static final long serialVersionUID = 1L

/ / original exception

Private Throwable cause

/ / Constructor

Public MyException (Throwable cause)

{

This.cause = cause

}

Public MyException (String sdinger Throwable cause)

{

Super (s)

This.cause = cause

}

/ / overload the printStackTrace method to print out the original exception stack information

Public void printStackTrace ()

{

If (cause! = null)

{

Cause.printStackTrace ()

}

Super.printStackTrace ()

}

Public void printStackTrace (PrintStream s)

{

If (cause! = null)

{

Cause.printStackTrace (s)

}

Super.printStackTrace (s)

}

Public void printStackTrace (PrintWriter s)

{

If (cause! = null)

{

Cause.printStackTrace (s)

}

Super.printStackTrace (s)

}

}

This is the end of the article on "how Java throws an exception in a method". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how Java throws an exception in the method". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report