Java from getting started to giving up JavaSE entry: exception,

Source: Internet
Author: User

Java from getting started to giving up JavaSE entry: exception,

Exception !!! Look at abnormal examples in life:

Under normal circumstances, it only takes 20 minutes to go to work from home to company! However, if you encounter problems such as congestion, road repair, or sudden spontaneous combustion, you cannot go to work normally. WhereProblems such as congestion or road repair or sudden spontaneous combustion of vehiclesIt is an exception.

If an exception occurs, you need to handle it. Otherwise, you can only stop working.

What does an exception in a Java program mean?

Errors in Java are classified into two types: Error and Exception)

ErrorGenerally, the IDE can discover and prompt before compilation. For example, you have to assign a large value to the integer variable:

 

This is a typical Error.

 

Program inAn exception occurs during running.!!! If you do not consider the handling of these exceptions during programming, the program will stop when exceptions occur. For example, in the following example, the Division by 0 error:

1234567 public static void main(String[] args) {    Scanner input = new Scanner(System.in);    System.out.print("Enter an integer :");    int i = input.nextInt();    int sum = 10/i;    System.out.println(sum);}

There is no problem with this code during compilation, But if you enter 0 at runtime, an exception will be prompted:

 

If an error occurs, it is okay to correct the encoding process. However, it is not controlled by the developer if an exception occurs (for example, above ), therefore, developers can only predict where exceptions may occur and handle them in advance.

1234567891011121314 public static void main(String[] args) {    Scanner input = new Scanner(System.in);    System.out.print("Enter an INTEGER (0 is not allowed ):");    int i = input.nextInt();    int sum = 0;    try {        sum = 10/i;    catch (Exception e) {        // TODO: handle exception        System.out.println("0 cannot be entered, 0 cannot be entered, and 0 cannot be entered !!! Do you understand Mandarin !!! ");    }         System.out.println(sum);}

Result:

 

We can find that no exception information is found in the results, and we have replaced it with our own prompt information.

 

The difference is as follows: if an exception occurs directly in front of the user, the user may no longer use your program. If you give a prompt, the user may continue to use it.

 

 

The exception concept has been introduced !!!, Next, let's take a look at how to handle exceptions in Java.

Common exceptions in Java include:

Of course, this is only a part of the list, and there are many exceptions that are already common. when you touch it, you 'd better check JDK.

 

Three methods to handle exceptions in Java:

  1. Try-catch-finally

  2. Throw andThrows

 

I. try-catch-finally

The try part is required to capture exceptions. Generally, code that may cause exceptions is put into it.

The catch part can be zero to multiple. It is used to identify and process the exception category. Generally, the exception handling code is put in it.

Finally part is optional. Code that must be executed no matter whether an exception exists.

1234567891011121314151617 int firstNum = 12int secondNum = 0;try {    int result = firstNum/secondNum;    System.out.println("The result of division of two numbers is :"+result)       }catch(ArithmeticException e) {    System.out.println("Arithmetic exception :");}catch(NumberFormatException e) {    System.out.println("Digit conversion exception");}catch(ArrayIndexOutOfBoundsException e){    System.out.println("Array subscript out-of-bounds exception");}catch(Exception e) {    System.out.println("Other exceptions");}finally{    System.out.println("I have to execute the drop. Please call it dad! ");}

 

2. thorw and throws

This keyword throws an exception and is not processed.

I asked James to bring me braised pork. James went to the canteen and found that there was no braised pork (this is equivalent to an exception). He didn't know how to handle it. Then he returned to the dormitory and told me that there was no braised pork, then I will try again.

1234567891011121314151617181920212223 public class XiaoMing {    // How to buy food    public void buyFood(String food) throws Exception{        // Use a collection to represent all the dishes in the canteen        List<String> foods = new ArrayList<String>();        foods.add("Green peppers and eggs");        foods.add("Green pepper shredded pork");        foods.add("Braised pork ribs");        foods.add("Potato cheers");        // Indicates whether the food status exists.        int state = 0;   // The default value is no 0. This food is not found. 1. This food is available.        for (String string : foods) {            if(food.equals(string)){                state = 1;                break;            }        }                 if(state==0){              throw new Exception("You have no food to eat! ");        }    }}

Compile the test code:

Should blind friends find out something wrong?

Yes, because throws Exception is added after the buyFood () method, IDE thinks that there is a very likely Exception during the call. We have to deal with it in two ways, either try-catch or throws Exception ).

In Java, apart from the exceptions defined in JDK, we can also customize exceptions. This is very simple. Define a class that inherits the Exception class, override the constructor of a parameter.

 

Okay, it will be enough for exceptions to come here. If you need to know more about it, please Baidu, haha!

 

"Software thinking" blog address:51CTO,BlogInterested friends can visit other related blog posts.

 

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.