Java BASICS (8)

Source: Internet
Author: User

Java BASICS (8)
I. Exceptions

An exception occurs when the program is running. The syntax error is not an exception.

1. Exception System

Throwable: AllError or exceptionThrowable class has two subclasses: 1, Error; 2, Exception.

1. All Exception classes are subclasses of java. lang. Exception,Controllable and manageable.

2. Java programs usually do not capture errors. Errors generally occur when a serious fault occurs.Outside the scope of Java program Processing. For example, JVM memory overflow.

3. Error indicates errors in the runtime environment.

4. Determine whether the system is an Exception or an Error by checking whether the subclass ends with an Exception or an Error.

Exception category

Runtime exception: RuntimeException and its subclass type.

If not processed (throw or try-catch ),No error is reported during compilation..

Non-runtime Exception: Exception and its subclass, except RuntimeException and its subclass.

If not processed (throw or try-catch ),Error reported during compilation.

2. Exception Handling

There are two methods to handle exceptions:

1. Handle try-catch by yourself

Write it in a place where an exception code may occur. If an exception occurs and an exception occurs, it will be captured and caught. The caught exception information will be placed in the abnormal variable. This way, you can handle this exception.

If no exception occurs, the system will not capture it, so proceed to the next step.

Syntax structure:

Try {// exceptions may occur} catch (exception type variable name) {// handle Exception Code}

Exception Handling Code:

1. Send the error message to the user. Directly call the printStackTract method to print the exception information.

2. Save the exception information to the log file for easy viewing.

2. Do not handle it by yourself and throw it out.

When thrown to JVM, it may also occur in the actual development process. When a method call method is called at many layers, the throw is like the one thrown by the caller at the previous layer.

Difference between throws and throw:

Throws indicates that an exception is thrown out, and the location is between () {} of the method. Features: Multiple exceptions are followed later.

Throw generates an exception object in the method. Feature: An exception object is followed, which is equivalent to return.

1 public class ThrowsDemo {2/** 3 * calculate two integers, divide them by 4 * @ param a 5 * @ param B 6 * @ throws Exception 7 */8 public void div (int, int B) throws Exception {// throw Exception 9 System. out. println (a/B); 10} 11 12/** 13 * test div14 */15 @ Test16 public void testDiv () throws Exception {17 div (1, 0 ); // print exception: java. lang. arithmeticException:/by zero18} 19}
3. Multi-Exception Handling

Statement structure:

1 try {2 // code that may be abnormal... 3} catch (exception type variable name) {4 // code for exception handling 5} catch (exception type variable name) {6 // code for exception handling 7} catch (exception type variable name) {8 // code for exception handling 9}
3. Exception finally statement

In addition to the above two exception structures, you can also add a finally

Syntax structure:

Try {// code that may have an exception} catch (exception type e) {// handle the exception: // 1 print to the console // 2 save to file // 3 may also throw a new exception} finally {}

What is the finally word? It indicates the final meaning.

1. Close the stream resource or release the lock-thread.

2. If the system exit (system. exit (0) statement is not executed before finally, the code here will always be executed.

3. Do not place a return statement here to return a data.

1 public class ExceptionTest {2/** 3 * Test if an exception occurs, the execution sequence of the program is 4 */5 @ Test 6 public void test1 () {7 try {8 System. out. println ("------ run 1 ------"); 9 System. out. println ("------ run 2 ------"); 10 System. out. println ("------ num ------" + (1/0); // after an exception occurs, do not run the following code, that is, do not print ------ execute 3------11 System. out. println ("------ execute 3 ------"); 12} catch (ArithmeticException e) {13 System. out. println ("------ catch1 ------"); 14 System. out. println ("------ catch2 ------"); 15 e. printStackTrace (); // print exception information java. lang. arithmeticException:/by zero16 System. out. println ("------ catch3 ------"); 17} finally {// execute 18 System regardless of whether an exception exists. out. println ("------ finally1 ------"); 19 System. out. println ("------ finally2 ------"); 20 System. out. println ("------ finally3 ------"); 21} 22} 23}
4. Custom exceptions

You have created an exception class and need to simulate a scenario that generates a custom exception:

1. customize an exception type,You need to create a class to inherit Exception or RuntimeException, Override the two constructor Methods.

2. simulate a scenario, create a custom exception object, and create an exception object through throw.

3. Use the above scenario to throw or process

1. customize an exception type.

1/** 2 * define the exception object by yourself. 3 */4 public class LoginUserException extends RuntimeException {5 public LoginUserException () {// override constructor 6 super (); 7} 8 9 public LoginUserException (String message) {// override constructor 10 super (message); 11} 12}

2. Use throw to generate a LoginUserException.

1 public class LoginUserTest {2 public String checkLogin (String username, String password) {3 if (! (Objects. equals (username, "user") {4 System. out. println ("------ run 1 ------"); 5 System. out. println ("------ run 2 ------"); 6 System. out. println ("------ execute 3 ------"); 7 throw new LoginUserException ("name is wrong"); // custom exception information, throw usage, generate an exception object LoginUserException 8} 9 return "return result"; 10} 11 12}

3. Test exception:

1 public class ExceptionTest {2/** 3 * Test custom exception 4 */5 @ Test 6 public void testCheckLogin () {7 LoginUserTest loginUserTest = new LoginUserTest (); 8 String s = loginUserTest. checkLogin ("user1", ""); 9 System. out. println ("---- s:" + s); // print exception: exception. loginUserException: name is wrong10} 11}

 

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.