Learn from teacher Wang (ii) try-catch

Source: Internet
Author: User

Try-catch Speaker: Wang Shaohua QQ group No.: 483773664
Learning Goals

Learn to use Try-catch to handle exceptions

First, what is an exception

An exception is an abnormal event that occurs during the course of a program's operation, which interrupts a running program.

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M01/7F/B3/wKioL1cprROwz155AAArs-wO4dI164.png " data_ue_src= "E:\My knowledge\temp\4ad586e7-7ded-42af-a023-177eb83ab528.png" >

Ii. What is exception handling

The exception handling mechanism is like some of the unexpected things we might encounter, and some of the things that we think about in advance.

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M00/7F/B3/wKioL1cprRTg5eCCAAB4bBKiga8979.jpg " data_ue_src= "E:\My knowledge\temp\7bd16491-43fe-4c9a-a051-98a17ac94ccc.jpg" >

When the program executes the code, in case of an exception, the program will handle the exception in accordance with the predetermined processing method, after the exception processing, the program continues to run.

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M02/7F/B5/wKiom1cprD_CP1dzAABHBD4I6pg710.png " data_ue_src= "E:\My knowledge\temp\1ae62973-3ec5-445d-86ea-7223cee2a480.png" >

Java exception handling is implemented by 5 keywords: try, catch, finally, throw, and throws

Third, using Try-catch to catch exceptions

The previous section of the example, business code and exception handling code mixed together, we want to have an "if block", can represent all error conditions, so that the program can handle all errors at once.

With this in mind, we try to separate the "handling exception code" from the "Processing Business code" chart.

Java provides the mechanism to put the business implementation code in a try block, all exception handling logic into the catch block for processing.

(i) using Try-catch to optimize the previous section example
123456789101112131415161718 public class Test2 {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);            System.out.print("请输入被除数:");                try {            int num1 = in.nextInt();            System.out.print("请输入除数:");            int num2 = in.nextInt();            System.out.println(String.format("%d / %d = %d",                    num1, num2, num1/ num2));            System.out.println("感谢使用本程序!");        } catch (Exception e) {            System.err.println("出现错误:被除数和除数必须是整数," +                    "除数不能为零。");            e.printStackTrace();        }    }}
(ii) Try-catch execution Process 1, no exception occurred

If all the statements in the try block execute normally without exception, then all statements in the CATCH block will not be executed. As shown below

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M02/7F/B3/wKioL1cprRSi7Vn0AAAOz5QKsqY607.png " data_ue_src= "E:\My knowledge\temp\45b795af-f1b3-49a2-85ce-5ee535f929ed.png" >

2, an exception occurred, was captured

If the TRY statement block encounters an exception during execution, and the exception matches the type of exception declared in the catch, the remaining code in the try block is ignored, and the corresponding catch block is executed.

A match is a catch that handles an exception type that exactly matches the generated exception type or its parent class.

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M00/7F/B5/wKiom1cprD-AV0pEAAA54C-guPA611.png " data_ue_src= "E:\My knowledge\temp\eb4bb0fc-1625-4d8e-a23e-28c4bfce9f6b.png" >

3, an exception occurred, did not match

If the TRY statement block encounters an exception during execution, and the exception thrown is not declared in the catch block, the program exits immediately.

Iv. try-catch Extension: One try with multiple catch blocks

To retrofit the example above

12345678910111213141516171819202122232425 public class Test2 {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);            System.out.print("请输入被除数:");               try {            int num1 = in.nextInt();            System.out.print("请输入除数:");            int num2 = in.nextInt();            System.out.println(String.format("%d / %d = %d",                    num1, num2, num1/ num2));            System.out.println("感谢使用本程序!");        }catch(InputMismatchException ie){            System.out.println("输入的类型不匹配");            ie.printStackTrace();        }catch (ArithmeticException e) {            System.err.println("除数不能为零");            e.printStackTrace();        }catch (Exception e) {            System.err.println("出现错误:被除数和除数必须是整数," +                    "除数不能为零。");            e.printStackTrace();        }    }}
V. Summary of the TRY-CATCH process

If an exception occurs when executing the business logic code in the try block, the system automatically generates an exception object (the next lesson explains the exception object in Java), which is referred to the Java runtime, which is called throwing an exception.

When the Java Runtime environment receives an exception object, it looks for a catch block that can handle the object, and if the appropriate catch block is found and the exception is handled by the catch block, the process is called a catch exception, and if the Java Runtime Environment cannot find the catch block that catches the exception, The runtime environment terminates and the Java program exits.

In the case of a try inside the exception, he will be based on the occurrence of the exception and catch inside the match (how to match, according to catch block from top to bottom), when it matches a catch block, he went directly into the catch block, followed by a catch block, It does not do any processing, jump directly past, all ignored.

When writing exception handling, be sure to put the exception range of small in front, the scope of large in the back, exception the root of this exception must be just in the last catch inside.










From for notes (Wiz)

Learn from teacher Wang (ii) try-catch

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.