Java (exception system and permission modifiers)

Source: Internet
Author: User
Tags finally block modifiers throw exception

Java Anomaly System exception system:
异常体系:--------| Throwable  所有错误或者异常的父类--------------| Error(错误)--------------| Exception(异常) 异常一般都通过代码处理 --------------------| 运行时异常: 如果一个方法内部抛出了一个运行时异常,那么方法上 可以声明也可以不 声明,调用者可以以处理也可以不处理。--------------------| 编译时异常(非运行时异常、受检异常): 如果一个方法内部抛出了一个编译时异常对象,那么方法上就必须要声明,而且调用者也必须要处理。运行时异常:RuntimeException以及RuntimeException子类 都是属于运行时异常。编译时异常:除了运行时异常就是编译异常。

How to differentiate between errors and exceptions:

1. If the program has abnormal information, if the class name of the unhealthy information ends with an error, then it must be a mistake.
2. If it ends in exception, then it must be an exception.

class  Demo10 { public  static  void  main  (string[] args)        {int  [] arr = null ; div     (4 , 0 , arr); } public  static  void  div< /span> (int  A, int  b,int  [] arr) {int  C;  c = A/b; //JVM in this sentence when the abnormal situation is found, then a corresponding exception object will be created.  System. out . println     ( + arr.length ); }}

When the JVM runs to A/b this statement, found that B is 0, the divisor is 0 in our real life is not normal situation, once the JVM found this abnormal situation, then the JVM will immediately create a corresponding exception object, And the Printstacktrace method of this exception object is called to handle.

Handling of Exceptions:

方式一:捕获处理方式二:抛出处理
Capture processing

Format of capture processing:

try{    可能发生异常的代码;}catch(捕获的异常类型 变量名){    处理异常的代码....}

Capture the details of the processing to be noted:

1. If the code in the try block has been processed, the code outside the Try-catch block will execute normally.
2. If there is an exception code in the try block, the code after the exception code in the try block will not execute.
3. A try block can be followed by multiple catch blocks, that is, a try block to catch a variety of types of exceptions.
4. A try block can catch a variety of types of exceptions, but the type of exception caught must be captured from small to large, or compile an error.

classDemo10 { Public Static void Main(string[] args) {int[] arr =NULL;Div(4,0, arr); } Public Static void Div(intAintBint[] arr) {intc =0;Try{c = A/b;//JVM in this sentence when the abnormal situation is found, then a corresponding exception object will be created. System. out.println("The length of the array:"+ arr.length); }Catch(ArithmeticException e) {//Handle exception code ....System. out.println("Exception handled ...."); System. out.println("toString:"+ E.toString()); }Catch(NullPointerException e) {System. out.println("A null pointer exception has occurred ...."); }Catch(Exception e) {System. out.println("I'm an emergency room, and I'm a cure!" "); } System. out.println("c="+C); }}

Is capturing exception a capture process?

错的,因为我们在现实开发中遇到不同的异常类型的时候,我往往会有不同的处理方式。所以要分开不同的异常类型处理。
Throw processing (throw throws)

Throw the details of the processing to note:

1. If an exception object is thrown inside a method, you must declare the throw on the method.
2. If a method that declares an exception is called, the caller must handle the exception.
3. If an exception object is thrown inside a method, the code after the throw statement is no longer executed (a method that encounters the Throw keyword will stop executing immediately).
4. In one case, only one type of exception object can be thrown.

Throw and throws two keywords:

The 1.throw keyword is used inside the method, and throws is used for method sound declarations.
The 2.throw keyword is used to throw an exception object inside a method, and the throws keyword is used to declare the throw exception type on the method declaration.
There can be only one exception object after the 3.throw keyword, and throws can declare several types of exceptions later.

Question: When to use throw processing? When to capture processing? What is the principle?

如果你需要通知到调用者,你代码出了问题,那么这时候就使用抛出处理.如果代码是直接与用户打交道遇到了异常千万不要再抛,再抛的话,就给了用户了。这时候就应该使用捕获处理。
classDemo11 { Public Static void Main(string[] args) {Try{int[] arr =NULL;Div(4,0, arr);//called a method that declares the exception type to be thrown}Catch(Exception e) {System. out.println("An exception has occurred ..."); E.Printstacktrace(); }        } Public Static void Div(intAintBint[] arr)throwsexception,nullpointerexception {if(b==0){Throw NewException ();//Throws an exception object ...}Else if(arr==NULL){Throw NewNullPointerException (); }intc = A/b; System. out.println("c="+C); }}
Finally block;

The finally block is used only if a try block is required to be used.

The code of the finally block executes in any case, except when the JVM exits.

Finally, it's a great way to work with resource releases, which ensures that resource files are released in any situation.

Three ways to combine a try block:

The first: the comparison is appropriate for exceptions to be handled, but no resources to release.

try{    可能发生异常的代码}catch(捕获的异常类型 变量名){    处理异常的代码}

Second: The comparison applies to code that has both exceptions to dispose of and resources to be freed.

try{    可能发生异常的代码}catch(捕获的异常类型 变量名){    处理异常的代码}finally{    释放资源的代码;}

Third: The comparison applies to the internal throw is a run-time exception, and there is a resource to be freed.

try{    可能发生异常的代码}finally{    释放资源的代码;}
classDemo5 { Public Static void Main(string[] args) {//system.out.println ("Hello world!");        Div(4,0); } Public Static void Div(intAintb) {Try{if(b==0) {System.Exit(0);//Exit JVM}intc = A/b; System. out.println("c="+ c); }Catch(Exception e) {System. out.println("An exception with a divisor of 0 ...");ThrowE }finally{System. out.println("The code for the Finall block was executed:"); }    }}
Custom exception Classes

Sun provides a lot of exception classes that we use to describe the various anomalies in the program, but it is not enough for sun to provide me with an exception class to describe all the anomalies in our real life, then we need to customize the exception class.

To customize the Exception class: Customize a class to inherit exception.

classNoipexceptionextendsexception{ Public noipexception(String message) {Super(message);//called a constructor that exception a parameter. }}classDemo2 { Public Static void Main(string[] args) {String IP ="192.168.10.100"; IP =NULL;Try{Feiq(IP);//If a method that declares an exception type is called, the caller must handle it. }Catch(Noipexception e) {e.Printstacktrace(); System. out.println("plug in the cable right now!" "); }    } Public Static void Feiq(String IP)throwsnoipexception{if(ip==NULL){Throw New  noipexception("no cable, little white!" "); } System. out.println("show friends List normally ..."); }}
Java package, permission modifier java package

The role of the package:

1. Resolve the problem of duplicate class names that create conflicts.
2. Easy release of software version.

To define the format of the package:

package 包名;

Package name naming specification: Package name all lowercase.

Things to note in a package statement:

The 1.package statement must be in the first statement in a Java file.
2. If a class adds a package statement, the class's full class name is: Package name. class Name
3. A single Java file can have only one package statement.

With the package, the class is accessed from the class:

Solution: Sum provides the guide-package statement to let us resolve the problem.

Guide Package statement function: Simplify writing. (Myth: Importing a class into memory)
Format of the guided package statement:

import 包名.类名; (导入xxx包中某个类)

Details to note in the Guide statement:

1. Multiple-sentence Guide statements can appear in a Java file.
2. "*" is a wildcard for the Guide package statement. You can match any of the class names.
3.import aa.*; is a sub-package that does not function under the AA package.

Recommended Use:

import 包名.类名;   因为使用*通配符会导致结构不清晰。
Permission modifiers

The permission modifier is the visibility of the scope that controls the decorated member.

            public(公共)    protected(受保护)    default(缺省)   private (大到小)同一个类      true             true                true         true同一个包      true             true                true         false  子父类        true             true                false        false不同包        true             false               false        false

Note: Only public and protected can be accessed under different packages, and protected must be accessible under an inheritance relationship.

Hit Jar Pack: A development tool (Jar.exe) that needs to be used with the JDK.

Usage of jar:

Use format:

jar cvf jar文件的名字  

Things to note in the jar pack:

1. After a program has finished the jar, you must specify the entry class on the manifest file: Format main-class: Package name. class Name
2.jar Package Double-click to run a program that works only for a graphical interface, the program for the console does not work.

The role of the jar file:

1. Easy for users to run a project quickly.
2. Provide tool classes to others in the form of a jar package.

If you use a class inside a jar package, you must first set the Classpath path.

JRE = jvm+ Core Class Library

package qq;import javax.swing.*;class Demo9 {    publicstaticvoidmain(String[] args) {        System.out.println("QQ程序..");        new JFrame("QQ程序");        frame.setSize(400,500);        frame.setVisible(true//设置窗口可见。        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    }}

Java (exception system and permission modifiers)

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.