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 deal with exceptions and errors in Java

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

Share

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

This article mainly introduces "how to deal with exceptions and errors in Java". In daily operation, I believe many people have doubts about how to deal with exceptions and errors in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to deal with exceptions and errors in Java". Next, please follow the editor to study!

Exceptions and errors:

Exception:

In Java, the errors in the program are mainly syntax errors and semantic errors. The errors that occur when a program is compiled and run are called exceptions. It is a way for VM (virtual machine) to inform you. In this way, VM lets you know that you (developer) have made a mistake and now have an opportunity to modify it. Exception classes are used in Java to represent exceptions, and different exception classes represent different exceptions. But all exceptions in Java have a base class called Exception.

Error:

It refers to a serious problem that a reasonable application cannot intercept. Most of them are abnormal. An error is a failure of VM (although it can be any system-level service). Therefore, errors are difficult to deal with, and the average developer (not you, of course) cannot handle these errors, such as memory overflows. As with exceptions, errors are represented by error classes in Java, and different error classes represent different errors. But all errors in Java have a base class called Error.

To sum up, we can know that the most essential difference between exceptions and errors is that the exception can be handled by the developer and the error comes from the system, which generally cannot be handled and does not need to be handled by our programmers.

1. An exception is an event that occurs during the execution of a program, which interrupts the operation of normal instructions.

two。 An act or an instance of deviating from acceptable code behavior.

Structural classification of exceptions:

1. Run-time exception (no exception checked)

2. Compile-time exception (checked for exception)

Running exceptions are RuntimeException;. The rest are compiled exceptions.

In Java, exception Exception and error Error have a common parent class, Throwable.

Error Exception

Several subclasses of runtimeException

1 、 java.lang.ArrayIndexOutOfBoundsException

Array index out of bounds exception. Thrown when the index of the array is negative or greater than or equal to the size of the array.

2 、 java.lang.ArithmeticException

The arithmetic condition is abnormal. For example: integer divided by zero and so on.

3 、 java.lang.NullPointerException

Null pointer exception. This exception is thrown when the application attempts to use null where the object is required. For example, call the instance method of the null object, and access the

Property, calculate the length of the null object, use throw statements to throw null, and so on

4 、 java.lang.ClassNotFoundException

Class exception not found. Thrown when the application attempts to construct a class based on a class name in the form of a string, and the class file with the corresponding name cannot be found after traversing CLASSPAH

The exception.

Handling of exceptions:

Try {} catch {}

Try {} catch {} finally {} blocks of finally code will be executed with or without exceptions

Try {} finally {} can also be used in combination, but catch {} finally {} cannot.

Note: in the inheritance relationship, the subclass overrides the methods of the parent class, and the scope of throwing exceptions cannot be broader than that of the parent class.

Abnormal use

In the use of exceptions, this part is mainly demonstration code, which we usually encounter in the process of writing code (only a small part of it, of course).

Example 1. This example is mainly through the comparison of two methods to demonstrate the execution flow of the code after the exception.

Public static void testException1 () {int [] ints = new int [] {1, 2, 3, 4}; System.out.println ("before exception occurs"); try {System.out.println (ints [4]); System.out.println ("am I lucky enough to execute it") / / after an exception occurs, the following code cannot be executed} catch (IndexOutOfBoundsException e) {System.out.println ("array out of bounds error");} System.out.println ("after exception") } / * output: array out of bounds errors often occur before exception occurs * / public static void testException2 () {int [] ints = new int [] {1, 2, 3, 4}; System.out.println ("before exception occurs"); System.out.println (ints [4]); System.out.println ("do I still have the honor to execute it") / / after an exception occurs, the code behind him cannot be executed}

First of all, point out the deficiency in the example. IndexOutofBoundsException is an unchecked exception, so there is no need for try. Catch... Show capture, but my goal is to handle the same exception differently to see how it will be different and the result (I can only make do with it here). When an exception occurs, the * * method just jumps out of the try block, but the code behind it will do the same. But the second kind is different. It directly jumps out of the method and is more tough. As we can see from the * methods, try... Catch... Is a "transactional" guarantee that ensures that the program finishes running under abnormal circumstances, and it also tells the programmer the details of the errors in the program (which sometimes depend on the programmer's design).

Example 2. Re-throw an exception

Public class Rethrow {public static void readFile (String file) throws FileNotFoundException {try {BufferedInputStream in = new BufferedInputStream (new FileInputStream (file));} catch (FileNotFoundException e) {e.printStackTrace (); System.err.println ("do not know how to handle the exception or do not want to handle it at all, but it is not appropriate not to handle it, this is to re-throw the exception to the higher level to handle") / / re-throw the exception throw e;}} public static void printFile (String file) {try {readFile (file);} catch (FileNotFoundException e) {e.printStackTrace ();}} public static void main (String [] args) {printFile ("D:/file");}}

The exception is well-intentioned, let's try to fix the program, but in reality we have little chance of fixing it, and we often use it to record error information. If you are tired of handling exceptions all the time, re-throwing the exception may be a good relief for you. Leave the exception intact to the next level, to the person who called the method, and let him think about it. In this way, the java exception (which, of course, refers to the detected exception) gives us a lot of trouble, even though it is well-intentioned.

Example 3. The use and loss of exception chain

ExceptionA,ExceptionB,ExceptionC public class ExceptionA extends Exception {public ExceptionA (String str) {super ();}} public class ExceptionB extends ExceptionA {public ExceptionB (String str) {super (str);}} public class ExceptionC extends ExceptionA {public ExceptionC (String str) {super (str);}}

Abnormal loss:

Public class NeverCaught {static void f () throws ExceptionB {throw new ExceptionB ("exception b");} static void g () throws ExceptionC {try {f ();} catch (ExceptionB e) {ExceptionC c = new ExceptionC ("exception a"); throw c } public static void main (String [] args) {try {g ();} catch (ExceptionC e) {e.printStackTrace ();} / * exception.ExceptionC at exception.NeverCaught.g (NeverCaught.java:12) at exception.NeverCaught.main (NeverCaught.java:19) * /

Why just print out ExceptionC and not print out ExceptionB? You'd better analyze this for yourself.

The above situation is equivalent to the absence of an anomaly, which is very disadvantageous in the process of making mistakes. So what should we do when we encounter the above situation? This is the opportunity for the exception chain to display its power: save the exception information and throw another exception without losing the original exception.

Public class NeverCaught {static void f () throws ExceptionB {throw new ExceptionB ("exception b");} static void g () throws ExceptionC {try {f ();} catch (ExceptionB e) {ExceptionC c = new ExceptionC ("exception a"); / / exception even c.initCause (e) Throw c;} public static void main (String [] args) {try {g ();} catch (ExceptionC e) {e.printStackTrace () } / * exception.ExceptionC at exception.NeverCaught.g (NeverCaught.java:12) at exception.NeverCaught.main (NeverCaught.java:21) Caused by: exception.ExceptionB at exception.NeverCaught.f (NeverCaught.java:5) at exception.NeverCaught.g (NeverCaught.java:10)... 1 more * /

The nature of this exception chain is common to all exceptions because the initCause () method inherits from Throwable.

Example 4. Clean-up work

Cleaning up is essential for us, because if there are resource-consuming operations, such as IO,JDBC. If we do not close correctly in time after using it, the consequences will be very serious, which means that there is a memory leak. The emergence of anomalies requires that we must design a mechanism that resources can be cleaned up timely and correctly under any circumstances. This is finally.

Public void readFile (String file) {BufferedReader reader = null; try {reader = new BufferedReader (new InputStreamReader (new FileInputStream (file); / / do some other work} catch (FileNotFoundException e) {e.printStackTrace ();} finally {try {reader.close () } catch (IOException e) {e.printStackTrace ();}

The example is very simple and is an example of reading a file. Such examples are also very common in JDBC operations. Therefore, I think the timely and correct cleaning of resources is one of the basic qualities of a programmer.)

Try... The finally structure is also a means to ensure that resources are properly closed. If you don't know what exceptions will occur during code execution that will prevent the resource from being cleaned, you can wrap the "suspicious" code in try and clean up the resource in finally. To give an example:

Public void readFile () {BufferedReader reader = null; try {reader = new BufferedReader (new InputStreamReader (new FileInputStream ("file")); / / do some other work / / close reader reader.close ();} catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}}

Let's note the difference between this method and the previous one. The next person may be used to shutting down reader as early as possible. But it often backfires, because exceptions can occur at any time before reader.close (), and such a code structure does not prevent any exceptions. Because the program will jump out where the exception occurs, the subsequent code cannot be executed (this should be proved by an example above). At this point we can use try. Finally to transform:

Public void readFile () {BufferedReader reader = null; try {try {reader = new BufferedReader (new InputStreamReader (new FileInputStream ("file"); / / do some other work / / close reader} finally {reader.close () }} catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}}

Shutting down resources early is good behavior, because the longer you take, the more likely you are to forget to close. In this way, in cooperation with try... Finally is guaranteed to be foolproof (don't bother, java is so regular).

In another case, if I want to open a file or create a JDBC connection in the constructor, because we want to use this resource in other methods, we cannot close the resource early in the constructor. Is there nothing we can do? The answer is no. Take a look at the following example:

Public class ResourceInConstructor {BufferedReader reader = null; public ResourceInConstructor () {try {reader = new BufferedReader (new InputStreamReader (new FileInputStream (");} catch (FileNotFoundException e) {e.printStackTrace () }} public void readFile () {try {while (reader.readLine ()! = null) {/ / do some work}} catch (IOException e) {e.printStackTrace () }} public void dispose () {try {reader.close ();} catch (IOException e) {e.printStackTrace ();} at this point, the study on "how to handle exceptions and errors in Java" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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