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 to handle exceptions in Java

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

Share

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

This article mainly explains "how to deal with exceptions in Java". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to deal with exceptions in Java".

Exception and error introduction

Let's take a look at the basic concepts first.

Exception refers to the abnormal phenomena in the process of running the program, such as user input error, divisor zero, non-existence of files to be processed, array subscript out of bounds, and so on. The essence of the exception mechanism is the mechanism that the program exits safely when an error occurs. In the exception handling mechanism of Java, many classes, called exception classes, are introduced to describe and handle exceptions. The exception class definition contains the information of this kind of exception and the method of handling the exception.

Java handles exceptions in an object-oriented way. Process:

Throw an exception: when an exception occurs when a method is executed, the method generates an object that represents the exception, stops the current execution path, and submits the exception object to JRE.

Catch an exception: after JRE gets the exception, it looks for the appropriate code to handle the exception. JRE looks in the method's call stack and starts backtracking from the method that generated the exception until the corresponding exception handling code is found.

Let's take a look at what the exception class mentioned earlier is!

In fact, all exception objects are an instance of the Throwable class. If the built-in exception class does not meet your needs, you can also create your own exception class. The root class of all exceptions is java.lang.Throwable. See what his family looks like.

There are two main schools under the Throwable class: Error and Exception.

Error is an error that cannot be handled by the program, indicating that there is a serious problem running the application, and the system JVM is already in an irrecoverable crash state. For example, talk about system problems such as memory overflows and thread deadlocks.

Exception is an exception that the program itself can handle. The Exception class is the parent class of all exception classes, and its subclasses correspond to a variety of possible exception events. In general, Java exceptions can be divided into: RuntimeException runtime exceptions CheckedException has checked for exceptions. Let's study these two exceptions.

Similarities and differences between RuntimeException and CheckedException

First, let's take a look at what a runtime exception is.

Such exceptions are usually caused by programming errors, so when writing a program, it is not required to use an exception handling mechanism to handle such exceptions, but often needs to be avoided by adding "logical handling".

For example, the following common exceptions:

ArithmeticException exception

Int bust 0; System.out.println (1Accord b); / / solution: if (baccalaure0) {System.out.println (1Accord b);}

NumberFormatException exception

String str = "1234abcf"; System.out.println (Integer.parseInt (str)); / / resolve: Pattern p = Pattern.compile ("^\\ dong$"); Matcher m = p.matcher (str); if (m.matches ()) {/ / if str matches the regular expression that represents a number, System.out.println (Integer.parseInt (str));}

ClassCastException exception

Animal a=new Dog (); Cat c = (Cat) a; / / solution: if (an instanceof Cat) {Cat c = (Cat) a;}

Two more points are added here to facilitate a better understanding of the mechanism and handling process of java exceptions.

After the method throws an exception, the runtime system turns to looking for a suitable exception handler (exception handler). A potential exception handler is a collection of methods stored in the call stack in turn when an exception occurs. When the exception type that the exception handler can handle matches the exception type thrown by the method, it is the appropriate exception handler.

The runtime system starts with the method in which the exception occurs, and then checks back the method in the call stack until it finds a method with a suitable exception handler and executes it. When the runtime system traverses the call stack and does not find a suitable exception handler, the runtime system terminates. At the same time, it means the termination of Java program.

Above we talked about what runtime exceptions are and some ways to handle them. Let's take a look at what checked exceptions are.

All exceptions that are not RuntimeException are collectively referred to as Checked Exception, also known as "checked exceptions", such as IOException, SQLException, and user-defined Exception exceptions. Such exceptions must be handled at compile time, otherwise they cannot be compiled.

There are usually two ways to handle exceptions:

Catch exceptions using "try/catch"

Use "throws" to declare an exception.

Let's talk about it in detail.

Exception handling

As mentioned above, there are usually two ways to handle exceptions. Let's take a look at the catch exception first.

Catching exceptions is achieved through three keywords: try-catch-finally. Use try to execute a program. If an exception occurs, the system throws an exception, which can be caught (catch) and handled by its type. The last step is to provide a unified exit for exception handling through finally statements, and all the code specified by finally will be executed.

This catch exception is also a problem that we often encounter during the interview. Now let's make a simple hint for each part.

(1) try

A try statement must have at least one catch statement block or one finally statement block. When the execution of the code for exception handling is finished, the try statement is not returned to execute the code that has not yet been executed.

(2) catch

Each try statement block can be accompanied by one or more catch statements to handle different types of exception objects that may be generated. Some common methods are introduced here, all of which inherit from the Throwable class.

The toString () method, which displays the class name of the exception and the cause of the exception.

The getMessage () method shows only the cause of the exception, but not the class name.

The printStackTrace () method is used to track the contents of the stack when an exception event occurs.

There is one thing to pay special attention to here, and that is the order in which catch catches exceptions:

If there is an inheritance relationship between exception classes, you should pay attention to the sequence arrangement. The more the top-level class is, the more it is placed below, otherwise the excess catch will be omitted directly. That is to say, the subclass exception is caught first and then the parent exception is caught.

(3) finally

It is always executed in the finally statement block, except when it encounters System.exit (0) to finish running the program. For this feature, we usually close open resources in finally, such as closing file streams, releasing database connections, and so on.

The finally statement executes even if the return statement exists in the try and catch blocks. Is to exit via return after executing the finally statement.

Here is a very classic interview question.

Public class Test {public static void main (String [] args) {System.out.println (new Test (). Test ());} static int test () {int x = 1; try {retun x;} finally {System.out.print ("jdbk" + x);} / ask for output results?

First explain the mystery of the existence here!

After reading the above description, we all know that when there is return in try and catch, finally still executes, so normally the answer to this question should be "jdbk2 2", but there is a trap, that is:

Finally is executed after the expression operation after return (instead of returning the value after the operation, the value to be returned is saved first. no matter what the code in finally, the returned value will not change, still the previously saved value), so the return value of the function is determined before the finally execution. So the correct answer should be "jdbk2 1".

It is also important to note that it is best not to include return in finally, otherwise the program will exit early and the return value is not the return value saved in try or catch.

Next, let's talk about declaring exceptions, which is relatively simple.

In some cases, the current method does not need to handle the exception that occurs, but is passed up to the method handler that calls it. If a method throws multiple checked exceptions, all exceptions must be listed at the beginning of the method, separated by commas.

Public static void readFile (String fileName) throws FileNotFoundException,IOException {}

What you need to pay attention to is:

When declaring an exception in method rewriting: when a subclass overrides a parent class method, if the parent class method has a declared exception, the exception scope of the subclass declaration cannot exceed that of the parent class declaration.

We usually declare exceptions in the server layer. Exceptions are generally caught in the controller layer or the data access layer.

Custom exception

Why should we customize exceptions? It's not because in the program, you may encounter that any standard exception class provided by JDK does not fully describe what we want to express. At this point, we can create our own exception class, that is, a custom exception class.

So how do we customize the exception class? I'm sure you can guess when you look at the family diagram of the abnormal class above. Yes, a custom exception class only needs to derive a subclass from the Exception class or its subclass. If you inherit the Exception class, the checked exception must be handled; if you don't want to handle it, you can have the custom exception class inherit the runtime exception RuntimeException class. In general, our custom exception class should contain two constructors: one is the default constructor, and the other is the constructor with details. Here's an example.

/ * * IllegalAgeException: illegal age anomaly, inheriting Exception class * / class IllegalAgeException extends Exception {/ / default constructor public IllegalAgeException () {} / / constructor with detailed information stored in message public IllegalAgeException (String message) {super (message) } public void setAge (int age) throws IllegalAgeException {if (age < 0) {throw new IllegalAgeException ("people's age should not be negative");} this.age = age;}

Finally, I would like to give you some suggestions on how to use the exception mechanism:

Avoid using exception handling instead of error handling, which reduces the clarity of the program and is inefficient.

Handling exceptions is not a substitute for simple testing-use exception mechanisms only in the case of exceptions.

Don't do small-grained exception handling-the entire task should be wrapped in a block of try statements.

Exceptions are often handled at a high level.

Thank you for reading, the above is the content of "how to deal with exceptions in Java". After the study of this article, I believe you have a deeper understanding of how to deal with exceptions in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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