Dark Horse programmer-object-oriented-exception, dark horse programmer object-oriented

Source: Internet
Author: User

Dark Horse programmer-object-oriented-exception, dark horse programmer object-oriented

------ Java training, Android training, iOS training, and. Net training. We look forward to communicating with you! -------

Exception: The program is abnormal during running.
Exception cause: the problem is also a specific thing in real life. It can also be described in the form of java classes and encapsulated into objects.
Actually, it is the embodiment of java's description of abnormal conditions.
There are two types of problems:
1. A serious problem
2. Non-serious problems
For serious cases, java uses the error class to describe
Write targeted code for errors.
For non-serious cases, java uses Exception to describe
You can use targeted processing methods to handle exceptions.
Both Error and Exception have some common content.
For example, abnormal information and causes
Throwable
| -- Error
| -- Exeption
Java provides special statements for processing.
Try {
Code to be detected
}
Catch (exception variables)
{
Code for exception handling (Handling Method)
}
Finally
{
Code that will be executed;
}
3. Perform common operations on the supplemented objects
String getMessage (); get exception information

Class Demo {int div (int a, int B) throws Exception // declares this function through the throws keyword in the function, which may cause problems {return a/B ;}} class ExceptionDemo {public static void main (String args []) {Demo d = new Demo (); try {int x = d. div (4, 1); System. out. println ("x =" + x);} catch (Exception e) {System. out. println ("zero"); System. out. println (e. getMessage (); System. out. println (e. toString (); // Exception name: exception information e. printStackTrace (); // Exception name, exception information, where an exception occurs. In fact, the default jvm Exception Handling Mechanism is to call the printStackTrace method and print the exception stack trace information} System. out. println ("over ");}}
Perform common operations on caught exceptions
String getMessage (): Get exception information
When a function declaration exception occurs, it increases security and allows the call to handle the exception.
For multi-exception handling:
1. When declaring an exception, it is recommended to declare a more specific exception so that the handling can be more specific.
2. When the other party declares several exceptions, it corresponds to several catch blocks. do not define Redundant catch blocks.
If an exception in multiple catch blocks has an inheritance relationship, the parent exception is placed at the bottom.
When performing catch processing, the catch must define a specific processing method.
Do not simply define e. printStackTrace ();
Do not simply define an output statement.

Class Demo {int div (int a, int B) throws ArithmeticException, arryIndexOutOfBoundsException // this function can be declared using the throws keyword. {int [] arr = new int [a]; System. out. println (arr [4]); return a/B;} class ExceptionDemo {public static void main (String args []) {Demo d = new Demo (); try {int x = d. div (5, 0); System. out. println ("x =" + x);} catch (Exception e) {System. out. println (e. toString);} catch (ArithmeticException e) {System. out. println (e. toString); System. out. println ("by zero");} catch (ArrIndexOutOfboundsException) {System. out. println ("e. toString); System. out. println ("badge out of bounds");} System. out. println ("over ");}}
This is because a special problem occurs in the project.
These problems are not encapsulated by java, so these special problems can be described as java's problem encapsulation ideas.
Customize exception encapsulation for specific problems
Custom exception
Requirements:
In this program, if the divisor is-1, the operation cannot be performed because the operation is incorrect.
You need to customize the description of this problem.
If throw throws an exception object in the function, corresponding processing actions are required.
Either try catch internally
Either let the caller process the Function
Generally, an exception occurs in the function and must be declared on the function.
The printed result contains only one field but no exception information.
Custom exception and undefined Information
How to define the exception information?
Because the operation on the exception information has been completed in the parent class
Therefore, as long as the Child class is constructed, the exception information is passed to the parent class through the super statement.
Then, you can use the getMessage method to customize the exception information.
Custom exception:
Must be a custom class inherited Exception
Cause of inherited Exception:
The exception class has one feature: Because the exception class and an object are thrown
They all have the possibility of throwing, which is unique in the Throwable system.
Only this system can be operated by throws and throw.
Difference between throws and throw:
Throws are used in functions.
Throw is used in the function.
The exception classes following throws can be separated by commas (,).
Throw is followed by an exception object
<Span style = "font-family: KaiTi_GB2312; font-size: 14px;"> class fushuException exten </span> ds Exception {private int value; fushuException () {super ;} fushuException (String msg, int value) {super (msg); this. value = value;} public int getValue () {return value;} class Demo {int div (int a, int B) throws fushuException // This is throws {if (B <0) throw new fushuException ("where the divisor is negative", B ); // This is throwreturn a/B;} class ExceptionDemo3 {public static void main (String args []) {Demo d = new Demo (); try {int x = d. div (4. -9); System. out. println ("x =" + x);} catch (fushuException e) {System. out. println (e. toString (); System. out. println ("the plural of the error is:" + e. getVaule);} System. out. println ("over ");}}
Exception has a special subclass Exception. RuntimeException runs abnormally.
If this exception is thrown in the function content, the function does not need to be declared.
If the exception is declared on the function, the caller can skip the process.
The reason why you do not need to declare a function is that the caller does not need to process it.
When this exception occurs, you want the program to stop because the program cannot continue to run during running. You want to stop the program and modify the code later.
If a custom exception occurs and the operation cannot be continued, the custom exception continues to inherit RuntimeException.
There are two types of exceptions:
1. Exceptions detected during compilation
2. Exceptions not detected during compilation (runtime exceptions, runtimeException, and subclasses)

Class fushuException extends RuntimeException {fushuException (String msg) {super (msg) ;}} class Demo {int div (int a, int B) throws Exception, throws ArithmeticException {if (B <0) throw new Exception ("negative"); if (B = 0) throw new ArithmeException ("excluded by zero "); return a/B ;}} class ExceptionDemo {public static void main (String args []) {Demo d = new Demo (); int x = d. div (4,-9); System. out. println ("x =" + x); System. out. println ("Over") ;}}/* class Person {public void checkName (String name) {// if (name. equals ("lisi") // NullPointerExceptionif ("lisi ". equals (name) // if (name! = Null & name. equals ("lisi") System. out. println ("YES"); elseSystem. out. println ("no") ;}} main () {Person p = new Person (); p. checkName (null);} */finally code block:/* finally code block: defines the code to be executed. It is usually used to close resources. */Class FuShuException extends Exception {FuShuException (String msg) {super (msg) ;}} class Demo {int div (int a, int B) throws FuShuException {if (B <0) throw new FuShuException ("divisor is negative"); return a/B ;}} class ExceptionDemo5 {public static void main (String [] args) {Demo d = new Demo (); try {int x = d. div (4,-1); System. out. println ("x =" + x);} catch (FuShuException e) {System. out. println (e. toString (); return; // System. exit (0 ); // System, exit. Jvm ended .} Finally {System. out. println ("finally"); // the code that will be executed will be stored in finally .} System. out. println ("over") ;}} class NoException extends Exception {} public void method () throws NoException {connect to the database; data operations; // throw new SQLException (); close the database; // whether the data operation is successful or not, you must disable the resource. Try {connect to the database; data operations; // throw new SQLException ();} catch (SQLException e) {exception handling will be performed on the database; throw new NoException ();} finally {close database;} catch is used to handle exceptions. If no catch is found, the exception has not been processed. If the exception is detected. It must be declared. Class Demo {public void method () {try {throw new Exception (); // No catch, must declare exception} finally {// close} class {public static void main (String args []) {System. out. println ("hello world ");}}
Exceptions are embodied in child parent class overwrite;
1. When a subclass overwrites the parent class, if the method of the parent class throws an exception, the override method of the subclass can only throw the exception of the parent class or the subclass of the exception.
2. If the parent class method throws multiple exceptions, the Child class can only throw a subset of the parent class exceptions when overwriting the method.
3. If no exception is thrown in the parent class or interface method, the subclass cannot overwrite the method.
If the subclass method has an exception. Try. It cannot be discarded.

class Aexception extends Exception{}class BException extends AException{}class CException extends Exception{}class fu{void show() throws AException{}}class test{void function(fu f){try{f.show();}catch(AException e){}}}class zi extends fu{void show thros CException{}}class {public static void main(String args[]){test t = new test();t.function(new zi());}}




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.