Java check exceptions and unchecked exceptions

Source: Internet
Author: User
public class ExceptionTypeTest {      public void doSomething()throws ArithmeticException{          System.out.println();      }      public static void main(){          ExceptionTypeTest ett = new ExceptionTypeTest();          ett.doSomething();      }  }
Question 1: Can the above program be compiled? And describe the reasons.
A: It can be compiled. Analysis: according to common sense, the dosomething method defines the arithmeticexception and calls this method in the main method. You should continue to throw or capture it. However, the arithmeticexception exception inherits the runtimeexception runtime exception. Java contains two types of exceptions: checked exception (check exception) and unchecked exception (unchecked exception
Check exceptions). For non-checked exceptions, it is also called runtimeexception (runtime exception). For runtime exceptions, the Java compiler does not require you to capture them or continue to throw them, however, for checked exception (check exception), you must capture or continue to throw it in the method.

Question 2: Can I compile the above program to change arithmeticexception to ioexception? And describe the reasons.
A: it cannot be compiled. Analysis: ioexception extends exception is a checked exception and must be captured or thrown.

Summary: Exceptions in Java are divided into two types: checked exception (check exception) and unchecked exception (not checked exception). For unchecked exceptions, it is also called runtimeexception (runtime exception ).
How to handle unchecked exceptions:
1. Capture
2. Continue to throw
3. Not handled

There are several ways to handle the checked exception (except runtimeexception:
1. Continue to throw. Negative methods can always be thrown to the Java Virtual Machine for processing.
2. Capture with try... catch
Note: The exception to be checked must be handled, captured, or thrown.

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.