Java exceptions and exception handling are simple to use

Source: Internet
Author: User
Tags finally block

An exception is an issue that prevents the current method or scope from continuing to execute while the program is running;

Any program can not guarantee the full normal operation, when an exception occurs, we need to deal with exceptions, especially some of the more important scenarios, exception handling logic will be more complex, such as: to prompt the user, save the current user action or changes, unfinished business rollback, release the resources used by the program.

In Java, the Throwable exception class is the ancestor of all exception classes, and any exception class inherits from the Throwable class;

The Throwable class has two subcategories: Error class, Exception class

The error exception class is a system exception, such as: Virtual machine error (VIRTUALMACHINEERROR), thread Deadlock (Threaddeath), etc., when the error class exception occurs, the program will crash

Exception is one of the most common exceptions in development, which can be errors in programming code, environmental issues, user input errors, etc.

Exception exceptions are generally divided into: run-time exceptions (RuntimeException) are also known as non-check exceptions, check exceptions;

Non-inspection exceptions are common: exceptions when outputting null pointers, array subscript out-of-bounds exceptions, type conversion exceptions, arithmetic exceptions (such as 0 as the denominator), runtime exceptions are automatically captured by the Java Virtual machine, and are automatically thrown, generally we write the code itself has problems, we need to improve our code to solve

The reasons for checking the exception are: File exception (no presence or permission), database connection exception, network connection exception, etc., this anomaly system is not automatically captured, we need to manually add the capture processing of the statement

  

We typically use Try-catch and try-catch-finally code blocks to handle exceptions

In a try block is a statement that can occur when an exception occurs, the program aborts execution when the program does, and throws an exception to the catch block for processing, and the catch handles the exception as needed, logs the error log, and so on, to see a simple example:

1 ImportJava.util.Scanner;2 3  Public classCeshi {4      Public Static voidMain (string[] args) {5         Try{6System.out.println ("Please enter an integer:");7Scanner input =NewScanner (system.in);8             intA =input.nextint ();9SYSTEM.OUT.PRINTLN ("You entered:" +a);Ten}Catch(Exception e) { OneSYSTEM.OUT.PRINTLN ("Input Exception"); AE.printstacktrace ();//Print exception Information -         } -SYSTEM.OUT.PRINTLN ("Program execution End"); the     } -}

This is the simplest exception handling, the user input is obtained through scanner, the program executes normally when the user enters the correct input, but the catch block is not executed, but if the user does not enter an integer, the exception is thrown to the catch block, and the Printstacktrace () can be used. The Try-catch method prints the specific exception, noting that the statement will be executed normally, regardless of whether the program is abnormal or not, and the error results are as follows:

According to the results we can see the input string "3s", throw an exception and prompt for an exception, but try-catch after the statement is executed normally, the thrown e.printstacktrace () will be printed at the end, It can be seen that the exception that occurred in the Ceshi.java is the exception that occurred in a receive input line statement, then the statement in all the try blocks after this line terminates execution

In addition, if the code in the try throws several types of exceptions, then we need multiple catch blocks to handle, and finally to do the aftercare work

1 ImportJava.util.Scanner;2 Importjava.util.InputMismatchException;3 Importjava.lang.ArithmeticException;4  Public classCeshi {5      Public Static voidMain (string[] args) {6Scanner input =NewScanner (system.in);7         Try{8System.out.println ("Please enter molecule:");9             intA =input.nextint ();TenSystem.out.println ("You enter the denominator:"); One             intb =input.nextint (); ASYSTEM.OUT.PRINTLN ("Calculation result:" + a*1.0/b); -}Catch(inputmismatchexception e) { -System.out.println ("Please enter an integer"); theE.printstacktrace ();//Print exception Information -}Catch(ArithmeticException e) { -SYSTEM.OUT.PRINTLN ("Denominator cannot be 0"); -E.printstacktrace ();//Print exception Information +}Catch(Exception e) { -System.out.println ("Other unknown exception"); + e.printstacktrace (); A}finally{ at input.close (); -         } -SYSTEM.OUT.PRINTLN ("Program execution End"); -     } -}

The above processing is more reasonable, first of all to ensure that the input is an integer, if it is an integer then the denominator of 0 will also throw an exception, and finally if we do not consider the exception, then through the exception parent class throws an exception, Catch exception block from top to bottom is usually from small to large or subclass to parent class exception class thrown, that is, from the scope of the details to the whole, exception exception class thrown must be placed in the last side, so that we can throw out all the exceptions encountered in the development, and finally block recommendations with, When an exception is encountered, he can release system resources that have not been previously operational, such as the shutdown input in the example, to improve the robustness of the program, if there are return values in the try and catch, then the statements in the finally will be returned to the caller in the return return value of the try and catch statement blocks , get the return value, we can output them in the program, but put in the try-catch-finally outside the return value when the finally is not obtained, can only get the preceding variable value

Java method exception thrown, because a lot of code we will write to the method, in order to facilitate management, we can handle the exception in the special method, so we can throw the exception in the method, you can write a method to simply throw the exception, the code is as follows:

1  Public voidDivideintAintbthrowsException {2     if(b = = 0){3         Throw NewException ("Divisor cannot be zero!") ");4}Else{5SYSTEM.OUT.PRINTLN ("result is:" + a*1.0/b);6     }7}

When the method is called, if an exception occurs, the exception is thrown into the called Block of statements, which we can handle at the time of invocation, such as:

 1  public  void   Complte () { try  { 3  divide (5,0); //  An exception occurs at this time, and the calling method throws the exception here  4 }catch   (Exception e) { //  Here catches the exception, throws the exception information defined in the method  6   7  }

This throws the exception in the method and handles it, and we can also throw it out of the Complte method, and throw an exception when the method is called, and the code is as follows:

 Public void throws Code               in Exception {/** * ellipsis method */Divide      (5,0);    // throw the exception inside to the location where the Complte method is called }

In this case, the exception continues to throw up, and finally the second paragraph of code to handle the exception, so the throws keyword declared this method throws an exception, with the Throw keyword to throw an exception

Custom exceptions

In addition to using system exceptions, we can also customize exceptions to suit the needs of our scenario by simply defining an exception class:

1  Public classCeshiexceptionextendsException {2 3      Publicceshiexception () {4         5     }6     7      Publicceshiexception (String message) {8         Super(message);9     }Ten}

Note that the custom exception class must inherit from the exception exception class, which defines a constructor with parameters to customize the exception information, which is constructed in order to instantiate the class with no errors by default, so we can use this custom exception class specifically in the method:

1  Public classChaintest {2 3     /**4 * Test1 (): Throws a custom exception5 * TEST2 (): Call Test1 (), catch custom exception, and wrap to run-time exception, throw new Exception6 * In the main method, call Test2 () to try to catch the exception thrown by the Test2 () method7      */8      Public Static voidMain (string[] args) {9Chaintest ct =Newchaintest ();Ten         Try{ One ct.test2 (); A}Catch(Exception e) { - e.printstacktrace (); -         } the     } -  -      Public voidTest1 ()throwsceshiexception{ -         Throw NewCeshiexception ("Original custom exception thrown"); +     } -      +      Public voidtest2 () { A         Try { at test1 (); -}Catch(ceshiexception e) { -             //TODO auto-generated Catch block -RuntimeException Newexc = -                 NewRuntimeException ("Throws a new run-time exception"); -Newexc.initcause (e);//referencing the original exception method, the exception chain in             ThrowNewexc; -         } to     } +}

As you can see from the code, the main method calls the Test2 method and catches the exception thrown by the Test2 method, and the Test2 method runs Test1 and catches the custom exception thrown in the Test1 method, and throws a new run-time exception to the Main method, The Test1 method, by declaring the custom exception class, implements the exception method thrown in the custom exception class, throws the exception into Test2, which is like a series of exception throws and exception handling, combined with a custom exception, which forms a small chain of exceptions, like a chain reaction that throws an exception

Finally, summing up, through the try-catch to deal with the exception, and can not avoid the existence of errors, but to maximize the robustness of the program, reduce the program errors brought about by the security risks and losses, we can not blindly use Try-catch to block the error, We should adopt reasonable logic algorithm to solve the insufficiency of program design, Try-catch is only a supplementary use, can not be overly dependent;

After the multiple catch block, it is better to add a catch (Exception e) {} to handle other unknown exceptions that may be omitted, and for less certain exceptions, Try-catch can be added to handle the potential risks;

For the exception must try to deal with, do not simply use E.printstacktrace (), to print the error message, so that the significance of the exception processing lost;

Specifically how to deal with exceptions, should be based on different business requirements and the type of exception to determine;

At last, we should be good at adding finally statement block behind Try-catch block, freeing up system resource, such as network connection, database connection, file closing, etc.

When and how to use the exception, but also need their own later in the development of slowly familiar

Java exceptions and exception handling are simple to use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.