Basic Learning day10 -- exception, package, basic day10 --

Source: Internet
Author: User

Basic Learning day10 -- exception, package, basic day10 --
I. Exceptions

1.1 exception Definition

Exception: -- abnormal, abnormal during program running

Exception cause: it is actually a specific thing in real life. The horse can express the description in the form of JAVA classes and encapsulate it into classes.

After Java describes abnormal conditions, the object is embodied.

Exception: two types.

One is serious: java uses the Error class to describe

For Error, it is generally not written to handle the required code.

Description of non-serious: java uses Exception class

Exception can be handled in a required way.

Example:

 

package com.day10.demo1;public class Demo1 {    public static void main(String[] args) {                System.out.println(div(5,0));        System.out.println("over");            }        public static int div(int a,int b){        return a/b;    }}

 

Result:

Exception in thread "main" java. lang. ArithmeticException:/by zero
At com. day10.demo1. Demo1.div (Demo1.java: 14)
At com. day10.demo1. Demo1.main (Demo1.java: 7)

An Arithmetic exception occurs because the divisor is 0.

 

1.2 exception Architecture

 

Java provides two main types of exceptions: runtime exception and checked exception. All checked exceptions are derived from the java. lang. exception class, while
Runtime exception is derived from the java. lang. RuntimeException or java. lang. Error class.

Their differences are manifested in two aspects: Mechanism and logic.

Runtime exceptions:

  • A runtime exception is thrown if no declaration is required during method definition.
  • You do not need to capture this runtime exception when calling this method.
  • Runtime exception is from java. lang. RuntimeException or
  • Derived from the java. lang. Error class.

Checked exceptions:

  • When defining a method, you must declare all possible checked exceptions.
  • When calling this method, you must capture its checked exception. Otherwise, you must
  • Pass its exception
  • Checked exception is derived from the java. lang. Exception class.

Logically, checked exceptions and runtime exception have different purposes.

Checked exception indicates an exception that can be directly handled by the caller. Checked exception forces you to capture it and handle this exception.

Runtime exception indicates a program error that the caller cannot handle or recover.

1.3 abnormal statements

Try {// statements that may cause exceptions} catch (exception-type exception object) {// write Exception Handling statements} [catch (exception-type exception object) {// write an exception handling statement} catch (exception-type exception object) {// write an exception handling statement }.... ] [Finally {program code that will certainly run ;}

Mainly used in combination: try-catch, try-catch-finally, and try-finally

 

 

1.4 Use try -- catch

No usage exception

 

Package com. day10.exception. demo1; public class Demo1 {public static void main (String [] args) {int x = 5; int y = 0; int index = div (x, y); System. out. println ("execution completed");} public static int div (int a, int B) {return a/B ;}}

 

Result:

Exception in thread "main" java. lang. ArithmeticException:/by zero

The output statement is not executed.

Use try -- catch

Package com. day10.exception. demo1; public class Demo1 {public static void main (String [] args) {int x = 5; int y = 0; try {int retsult = x/y ;} catch (Exception e) {e. printStackTrace ();} System. out. println ("execution completed ");}}

Result:

Java. lang. ArithmeticException:/by zero
At com. day10.exception. demo1.Demo1. main (Demo1.java: 10)
Execution completed

The code behind the Exception Code block is executed.

When an exception occurs in the code in try-, jump to the catch Block to catch the exception. After the exception block is completed, run the Code following the exception block.

 

 

1.5. try-catch-finally

Package com. day10.exception. demo1; public class Demo1 {public static void main (String [] args) {int x = 5; int y = 0; try {int retsult = x/y; System. out. println ("no Exception occurred when I executed");} catch (Exception e) {System. out. println ("exception occurred"); e. printStackTrace ();} finally {System. out. println ("I will be executed");} System. out. println ("execution completed ");}}

Result:

An exception occurred.
I will be executed
Execution completed
Java. lang. ArithmeticException:/by zero
At com. day10.exception. demo1.Demo1. main (Demo1.java: 10)

 

1.6. Code in finally is not executed

 

Package com. day10.exception. demo1; public class Demo1 {public static void main (String [] args) {int x = 5; int y = 0; try {int retsult = x/y; System. out. println ("no Exception occurred when I executed");} catch (Exception e) {System. out. println ("exception occurred"); e. printStackTrace (); System. exit (0); // or-1} finally {System. out. println ("I will be executed");} System. out. println ("execution completed ");}}

 

Java. lang. ArithmeticException:/by zero at com. day10.exception. demo1.Demo1. main (Demo1.java: 10)

1.7. How to execute a return statement?

Return in try

 

package com.day10.exception.demo1;public class Demo2 {    public static void main(String[] args) {                System.out.println(getException());    }    public static int getException(){                try {            int x=5;            System.out.println("try return");            return x;        } catch (Exception e) {            System.out.println("catch return");        }finally{            System.out.println("finally return");        }        return 0;    }}

 

Result:

Try return
Finally return
5

Return in try does not affect code execution in finally.

 

Return in catch

 

package com.day10.exception.demo1;public class Demo2 {    public static void main(String[] args) {                System.out.println(getException());    }    public static int getException(){        int x=5;        try {            int result=x/0;            System.out.println("try return");            return x;        } catch (Exception e) {            System.out.println("catch return");            return ++x;        }finally{            System.out.println("finally return");        }    }}

 

Result:

Catch return
Finally return
6

 

The return in catch will not affect the execution in finally, but the returned result will be the return result in catch and will overwrite the result in try.

Return in finally

 

package com.day10.exception.demo1;public class Demo2 {    public static void main(String[] args) {                System.out.println(getException());    }    public static int getException(){        int x=5;        try {            int result=x/0;            System.out.println("try return");            return x;        } catch (Exception e) {            System.out.println("catch return");            return ++x;        }finally{            System.out.println("finally return");            return ++x;        }    }}

 

Result:

Catch return
Finally return
7

The return in finally does not affect the execution in finally, but the returned result will be the return result in finally and will overwrite the results in try and catch.

 

 

 

1.8. Multiple catch Blocks

Exception exceptions must be placed at the top of the buckle. Otherwise, exceptions in the lower part cannot be executed. Only execution of the parent class will be executed, and exceptions in the subclass will not be caught.

 

Package com. day10.exception. demo1; import java. util. inputMismatchException; import java. util. operator;/** calculate the quotient of two integers. When an exception occurs, how does the program handle */public class Demo2 {public static void main (String [] args) {// obtain the input from the keyboard. try {inputs input = new inputs (System. in); System. out. println ("Enter dividend:"); int num1 = input. nextInt (); System. out. println ("Enter the divisor:"); int num2 = input. nextInt (); int result = num1/num2; System. out. Println (num1 + "and" + num2 + "OPERATOR:" + result);} catch (InputMismatchException e) {System. out. println ("the input is not a number"); e. printStackTrace ();} catch (ArithmeticException e) {System. out. println ("the divisor cannot be 0"); e. printStackTrace ();} catch (Exception e) {System. out. println ("other errors! "); E. printStackTrace () ;}finally {System. out. println (" Thank you! ");}}}

 

Result 1:

Enter the divisor:
Fsd
The input is not a number.
Thank you!
Java. util. InputMismatchException

Result 2:

Enter the divisor:
9
Enter the divisor:
0
The divisor cannot be 0.
Thank you!
Java. lang. ArithmeticException:/by zero

Result 3:

Enter the divisor:
7
Enter the divisor:
3
7 and 3 vendors: 2
Thank you!

1.9 custom exceptions

Custom exceptions only need to inherit the Exception class

Define the Exception class. You only need to inherit the Exception class.

Of course, it can inherit other types, such as Exception, Throwable, RuntimeException, and its subclass. It inherits Exception, Throwable, and effect. If the caller is not required to handle the thrown Exception, it can inherit RuntimeException and its subclass.

 

During the call, only throw new custom exception name (information) is required)

 

 

Package com. day10.exception. demo1;/*** custom Exception * @ author denny **/public class MyException extends Exception {public MyException () {super ();} public MyException (String message, throwable cause, boolean enableSuppression, boolean writableStackTrace) {super (message, cause, enableSuppression, writableStackTrace);} public MyException (String message, Throwable cause) {super (message, cause );} public MyException (String message) {super (message);} public MyException (Throwable cause) {super (cause );}}

The above is a computing definition exception. Use the constructor to reload it.

1.10 throw and throws throw an exception

 

An error occurred while using the preceding calculation definition.

Package com. day10.exception. demo1; public class Person {private String name; private int age; private String gender; public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {if (age> = 0 & age <= 150) {this. age = age;} else {try {throw new MyException ("the age must be between 0 and 50");} catch (MyException E) {e. printStackTrace () ;}} public String getGender () {return gender;} public void setGender (String gender) throws MyException {// if (gender. equals ("male") | gender. equals ("female") {this. gender = gender;} else {throw new MyException ("gender can only be male or female! ");/* Throw can throw an exception in the method body, but it must be captured or thrown with throws */} public void printSelf () {System. out. println ("name:" + this. name + "Gender:" + this. gender + "Age:" + this. age );}}

 

Test class

Package com. day10.exception. demo1; public class PersonTest {public static void main (String [] args) {Person p = new Person (); try {p. setName ("Zhang San"); p. setAge (200); p. setGender ("demon");} catch (MyException e) {e. getMessage (); // get exception information} finally {}}}

Result: com. day10.exception. demo1.MyException: The age must be between 0 and 50 years old.

The following gender assignment is not executed because an exception has occurred when the age assignment is executed.

Package com. day10.exception. demo1; public class PersonTest {public static void main (String [] args) {Person p = new Person (); try {p. setName ("Zhang San"); p. setAge (20); p. setGender ("demon"); p. printSelf ();} catch (MyException e) {// System. out. println (e. getMessage (); // get exception information e. printStackTrace () ;}finally {}}}

Result:

Com. day10.exception. demo1.MyException: The gender can only be male or female!

 

Ii. Package

2.1 package meaning

File classification management, similar to folders in windows, with the same package on the same Layer

Provides a multi-layer namespace for the class. The file names of the same folder are different and hierarchical,

The first line of the program file.

The full name of the class name is package name. Class Name.

Package is also a form of encapsulation

2.2. Package Definition

Package name,

The package name must be in lower case. You can use the. decimal point to define a multi-level package.

Must be placed in the first line of the Code

Javac-d. java file name. java. indicates the current folder directory

The appearance of the package can separate the java class file from the source file. You only need to copy the class file and run it.

Do not repeat the defined package name

2.3 Package Import

Import package name. Class Name

2.4 access permissions between packages

 

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.