Understand two types of exceptions in Java

Source: Internet
Author: User

Exceptions in Java are divided into two different situations: 1. exceptions that the compiler forces the user to handle; 2. Non-mandatory exceptions. (Java is the only language that enables the compiler to force the user to handle exceptions)

For example:

Imagine a beach where lifeguards manage areas separately. If you want to swim without a life jacket, the lifeguard will stop you from entering the sea and force you to wear a life jacket before you go down the sea. In Java, the compiler is like a lifeguard, and try and catch blocks act like a life jacket. We can regard it as "Force user execution ";

Another situation: this beach has an area where swimming is generally not dangerous, but it is not absolutely not dangerous, so when swimming in this area, lifeguard will not force you to wear a life jacket, but it will be safer to wear it. This situation can be understood as "non-mandatory ".

First case: in Java, when an unhandled exception exists in the called method (that is, throws "exception class name" is used in the method definition "), exceptions must be caught (wear a life jacket );

Case 2: There is a textfield in the interface that allows the user to enter the age. The Int variable is used in the program to obtain: int age = integer. parseint (textage. gettext (); in this case, if the user inputs non-numeric data, an exception is generated. Otherwise, no exception is generated. Therefore, it is safer to use exception capture (that is, it is best to wear a life jacket)

The above is my understanding, hoping to help you.

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.