Introduction to exceptions and errors in java learning, exception capturing, exception throwing, custom exceptions, finally keywords (small records in java learning), and finally keywords

Source: Internet
Author: User
Tags finally block

Introduction to exceptions and errors in java learning, exception capturing, exception throwing, custom exceptions, finally keywords (small records in java learning), and finally keywords

Introduction to exceptions and errors in java learning, exception capturing, exception throwing, custom exceptions, and finally keywords (small records in java learning)

Author: Star)

 

Exception :(There is an exception in the java. lang APIs, and there are many)

In a Java program, the program is abnormal. This is called an exception.

Java is an object-oriented language. Everything can be described using classes. The same exception is also a kind of thing. Java provides many exception classes.

The accumulation of multiple exceptions is an exception system.

Throwable: it is the parent class of the exception class, superclass. Exception and error.

The exception system is as follows (illustration ):


We mainly learn three methods of Thorwable:

1. toString ();A brief description of Thorwable: complete Class Name: package name + class name

2. getMessage ();String of Thorwable's detailed information

3. printStackTrace (); prints abnormal stack memory information

 

package study;
public class star {
public static void main(String[] args) {
Throwable t = new throwable ("this is an exception, please handle"); / / this is the exception object, so the exception / / parameter can pass a GetMessage
System. Out. Println (t.tostring()); / / Java. Lang.throwable: This is an exception, please handle
System. Out. Println (t.getmessage()); / / this is an exception, please handle
t. Printstacktrace(); / / abnormal stack memory information is printed
}
}

 

Error: the error is generally caused by a Java virtual machine or hardware. It is called an error. Therefore, we generally do not use code to handle errors.

For example, byte [] buf = new byte [1024*1024*1024];

// No syntax error. By default, the java Virtual Machine can only manage 64 MB of memory. Therefore, we call it an error because of problems caused by java or hardware.

Exception: All exceptions are inherited fromException.

Differences between errors and exceptions:

For example, java. lang. OutOfMemoryError is a type of Error (ended with an Error)

AclNotFoundException this is an exception (The end of Exception, except that the end of Error is)

Exception Handling:

Method 1: capture exceptions

Exception capture processing format:

Try {

Code that may cause exceptions

} Catch (catch exception type variable name ){

Code for handling exceptions

}

1 package study;
Two
Three
4 public class star {
5     public static void main(String[] args) { 
Six
7         int[] arr = {1,2};
8 arr = null; / / java.lang.nullpointerexception null pointer exception
9         test(4, 0,arr);//java.lang.ArithmeticException: / by zero
10}
11     public static void test(int a,int b,int[] arr){
Twelve
Thirteen
14 / / catch exception handling
15         int c = 0;
Sixteen
17         try {
18 / / unexpected code may appear
19             System.out.println(arr.length);
20             c = a/b;
21         } catch (ArithmeticException e1) {
22 system. Out. Println ("handle exceptions with a divisor of 0");
23         } catch(NullPointerException e2){
24 system. Out. Println ("handle null pointer exception");
25} catch (exception E) {/ / the parent class should be placed at the back. If the exception is handled at the front, the subsequent exceptions will not be executed. In this way, this can handle other exceptions not mentioned above.
26 system. Out. Println ("all exceptions are handled here");
27}
Twenty-eight
29         System.out.print("c = "+c);
30}
31}
Note:

1. If a problem occurs in the try method, the code other than try-catch will be executed.

2. The code in catch will only be executed if an exception occurs in the code in try.

3. Multiple catch blocks can be used in a try, that is, a try can handle the exception.

4. try capture exceptions are captured in ascending order. At the bottom is the largest exception of the parent class. Otherwise, an error is reported.

Capture exceptions:

Currently, it cannot be seen that it is often used when learning JavaEE (the knowledge points will be supplemented later );

Why not directly use the biggest exception:

In order for us to precisely and quickly find the root cause of the error. For example, if a null pointer is abnormal and the maximum exception is used, it cannot be seen that the NULL pointer is abnormal.

Method 2: throw an exception

Throws two key keywords for exception handling (throw and throws)

Note the following when using throw and throws:

1. The throw keyword is used in the method, and throws is used in the method declaration.

2. The throw keyword is used to throw an exception inside the method, and throws is used to throw an exception on the method declaration.

3. There can only be one exception behind the throw keyword. throws can declare multiple exceptions.

Note the following when throwing an exception:

1. If you throw an exception object in the method, you must throw an exception in the method declaration.

2. If a method calls a method that throws an exception, the caller must handle the thrown exception.

3. If an exception occurs in a method, the code after throw will not be executed again.

4. Only one exception can be thrown in one case. (See the code for details) If there are multiple exceptions, take the exception closest to it.

When to throw an exception, and when not to throw an exception?

You need to notify the caller (who calls your code) that your code may be faulty. In this case, you need to throw this exception and let the caller solve the problem.

If the code is directly dealing with users and encounters an exception, you need to process the code. The user does not know what the code means, and you need to change the method to let the user know what it means.

 

1 package study;
Two
Three
4 public class star {
5     public static void main(String[] args) {
6         try {
7             int[] arr = {1,2};
8             arr = null;
9             test(4, 0,arr);
10         } catch (ArithmeticException e) {
11 system. Out. Println ("processing exception");
12}
Thirteen
14}
15 public static void test (int a, int b, int [] ARR) throws arithmeticexception, NullPointerException {/ / / be sure to declare this exception
16 / / try catch is used to handle exceptions, and then the following code continues to execute
17 / / now it's time to throw out the abnormal code to the caller (the upper level here is in the main function)
Eighteen
19         if (b == 0) {
20 throw new arithmeticexception(); / / there may be this wrong object, throw it out
21} / * else if (arr = = null) {/ / if the code above is executed, the code after throw will not be executed again
22             throw new NullPointerException();
23         } */
Twenty-four
25 system. Out. Println ("cheerleading");
26             int c = a/b;
27 / / system. Out. Println (c); / / if it's thrown out, C doesn't make sense and doesn't need to be printed
28}
29}

Custom exception

Requirement: When feiQ (feiqiu) is launched, the system finds that the network cable is not plugged in. In this case, you need to throw an exception yourself (prompting the programmer that the network cable is not plugged in );

Premise: custom a class inherits from Exception

Problem: Sometimes an exception must be declared, and sometimes an exception cannot be declared.

Exception architecture: Exception is followed by runtime Exception and compilation Exception;

Running is an exception: When a running exception is thrown, you do not need to declare an exception on the method, or the caller can not handle it.

Compile-time exception: When a compile-time exception is thrown, an exception must be declared on the method and the caller must handle it.

How to differentiate between compile time and runtime exceptions:

These are runtime exceptions: RuntimeException itself, or any subclass that inherits this exception is runtime exceptions.

Except for runtime exceptions, all others are compile-time exceptions. Exception is an Exception during compilation.

1 class NoIPException extends Exception{
Two
3 / / user defined Exceptions without network cable
4     public NoIPException(String message) {
5 super (message); / / if you do not write the default, call the empty constructor of the parent class
6}
7}
Eight
9 public class star {
10     public static void main(String[] args) throws NoIPException{
Eleven
12 / / using feiq
13         String ip = "192.168.10.100";
Fourteen
15 test (IP); / / here is an error. There are two options. You can continue to throw and handle it.
16 throw new noipexception ("please plug in the network cable if it's not plugged in"); / / throwing it again here is the Java virtual machine
17}
18     public static void test(String ip) throws NoIPException{
19         if (ip == null) {
20 throw new noipexception ("do not plug in the network cable, please plug in the network cable"); / / thrown to the caller (main function)
21}
22}
23}

Finally keyword

The finally block and try are used together.

Finally: no matter what the problem occurs, the finally code will be executed. The Code will not be executed unless the jvm exits.

The role of finally: finally is very suitable for the release of resources, so that I can release this resource file at any time.

1 package study;
Two
3 public class star {
4     public static void main(String[] args) {
5          try{
Six
7              test(10,0);
Eight
9           }catch(Exception e) {
Ten
11 system. Out. Println ("processing...");
12           }
13}
14     public static void test (int a, int b) throws Exception{
Fifteen
16         int c= 0;
17         try
18             {
19                 c = a / b;
20             }
21             catch (Exception e)
22             {
Twenty-three
24 / / system. Exit (0); / / exit the JVM
25 return; / / still execute the code in finally
26             }
27             finally {
28               System.out.println("c = "+c);
29             }
30}
31} 

 


Related Article

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.