Java Learning Note 16--exception

Source: Internet
Author: User

Java Learning Note 16--exception

Abnormal

An exception that causes the program to run a flow of instructions, if the exception is not properly handled, it can cause the program to break execution, causing unnecessary loss,

Therefore, in the design of the program must consider the occurrence of various anomalies, and correct the corresponding treatment, so as to ensure that the normal implementation of the program.

Inheritance structure for exception classes

In the entire Java exception structure, there are actually the following two most commonly used classes:Exception, Error, these two classes are all Throwable subclasses

Exception: Generally represents a problem in the program, you can directly use the Try...catch processing.

Error: General refers to a JVM error that cannot be handled in the program.

Custom exception Classes

You can complete a custom exception class only if you inherit exception. Because the standard exception classes are provided in Java (including some exception information, etc.)

You can customize the exception class if you need to define the exception information you want.

[Java]View Plaincopy
  1. Package com.itmyhome;
  2. Import Java.util.Scanner;
  3. Class MyException extends Exception { //Custom exception class
  4. Public myexception (String name) {
  5. super (name); //Call the parent class construct
  6. }
  7. }
  8. Public class T3 {
  9. /** 
  10. * @param args
  11. */
  12. public static void Main (string[] args) {
  13. //TODO auto-generated method stub
  14. Scanner scan = new Scanner (system.in);
  15. System.out.print ("Please enter the divisor:");
  16. int i = Scan.nextint ();
  17. System.out.print ("Please enter dividend:");
  18. Int J = Scan.nextint ();
  19. try {
  20. if (j = = 0) {
  21. throw New MyException ("dividend cannot be 0"); //Throw a custom exception
  22. } Else {
  23. System.out.println (i/j);
  24. }
  25. } catch (Exception e) {
  26. E.printstacktrace ();
  27. } finally {
  28. }
  29. }
  30. }


A few common interview questions:

1. There is a return statement in try {}, then the code in the finally {} immediately after this try will not be executed, when executed, before or after the return?

Will execute before the return.

See below for two examples

[Java]View Plaincopy
  1. Public class T {
  2. public static void Main (string[] args) {
  3. System.out.println (new T (). Test ());
  4. }
  5. static int Test () {
  6. int x = 1;
  7. try {
  8. return x;
  9. } finally {
  10. ++x;
  11. }
  12. }
  13. }

Output returned 1

[Java]View Plaincopy
  1. Public class T {
  2. public static void Main (string[] args) {
  3. //TODO auto-generated method stub
  4. SYSTEM.OUT.PRINTLN (Test ());
  5. }
  6. public static int Test () {
  7. try{
  8. return 1;
  9. }finally{
  10. return 2;
  11. }
  12. }
  13. }

Output returned 2

The function called by the return statement in try executes before the function called in Finally, that is, the return statement executes first, and the finally statement executes, so the return result is 2.

Return does not return the function immediately, but the return statement executes, and the returned result is placed in the function stack, where the function is not returned immediately, to be executed

The finally statement does not actually begin to return.

2, the difference between final,finally,finalize

Final is used to declare properties, methods, and classes, respectively, that the property is immutable, that the method is not overridden, and that the class is not inheritable.

Finally is part of the exception-handling statement structure, which indicates that it is always executed.

Finalize is a method of the object class that, when executed by the garbage collector, calls this method of the reclaimed object, and can override this method to provide garbage collection for other resource recycling

such as closing files, and so on. The JVM does not guarantee that this method is always called.

3. What are the similarities and differences between abnormal operation and general anomaly?

An exception represents an unhealthy state that may occur during a program's run, and a run-time exception that represents an exception that may be encountered in a typical operation of a virtual machine is a common run error.

The Java compiler requires the method to declare a non-runtime exception that might occur, but does not require that a runtime exception that is not caught to be thrown must be declared.

4. What is the difference between error and exception?

Error indicates a serious problem in situations where recovery is not impossible but difficult. such as memory overflow, it is impossible to expect the program to come out of this situation.

Exception represents a design or implementation issue.

That is, it means that if the program runs normally, it never happens.

5, write out the most common 5 runtime exception

Classcastexception,indexoutofboundsexception,nullpointerexception,arithmeticexception,illegalargumentexception

6. Simple principle and application of exception handling mechanism in Java

Exceptions are abnormal conditions or errors that occur when the Java program is run (not compiled), and Java uses an object-oriented approach to handle exceptions, which take each exception that occurs in the program

are also encapsulated into an object that contains information about the exception.

Java classifies exceptions, different types of exceptions are represented by different Java classes, and the root class for all exceptions is java.lang.throwable,throwable and derives

Two subclass error and Exception,error represent a serious problem that the application itself cannot overcome and recover, such as a system problem such as memory overflow and thread deadlock.

Exception said that the program can also overcome and restore the problem, which is divided into system anomalies and common anomalies, system anomalies are the defects of the software itself caused by the problem, that is, soft

The problem that the software user is not able to overcome and recover from the lack of consideration of the developer , but in this case the software system can continue to run or let the software die

Drop, such as array out of bounds (arrayindexofoutofboundsexception) null pointer exception (NULLPOINTEREXCEPTION) class conversion exception (ClassCastException)

Ordinary exception is the number or exception of the running environment caused by the problem, is the user can overcome problems such as network disconnection, insufficient disk space, such an exception occurs after the process

Order should not die.

Java provides a different solution for system exceptions and common exceptions, and the compiler enforces common exceptions that must be try...catch to handle the goods with throws declarations continue to be thrown at the upper calling method

, so common anomalies are also known as checked anomalies, two system exceptions can be handled or not handled, so the compiler does not enforce try...catch processing or throws sound

System anomalies are also known as unchecked anomalies.

Java Learning Note 16--exception

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.