Java Programming Idea (ix)--Pass Exception handling error (1)

Source: Internet
Author: User

The former saw a programming learning Method- Rubber Duck Debugging Method , is to take a small yellow duck.





Talk to him in person, tell him about your programming ideas, if you don't have a rubber duck or a girlfriend who can listen to you java,c,cpp, front end, Io, system kernel, assembly, data structure, computer network, then blogging is also a good way to comb your own ideas.


The basic idea of Java is that poorly structured code cannot run.


In fact, I also do not understand why to get a such thing out, in fact, as the book said, "abnormal" has "surprised" the meaning, the problem arises, we do not know how to deal with, but can not ignore, we could stop to see if there are other places to deal with such problems. This can reduce the complexity of the code, if you do not use exceptions, you need to check and handle the error in the program, after using the exception, you do not have to check under the method, the exception mechanism to catch errors.

The so-called "describe what happens during normal execution" and "What's Wrong" code separation.


To give a simple example:

public class Box {public    static void Main (string[] args) {        int i[] = new Int[4];        Box.change (I, 5, 1);    }    static void Change (int[] I, int index,int value) {        I[index] = value;    }}

If this argument goes beyond the bounds of the array, this is the wrong thing to do, so you can handle it in a method, add:

    static void Change (int[] I, int index,int value) {        if (index>i.length) {            System.out.println ("Indexoutofbound ");            return;        }        I[index] = value;    }

the processing here is relatively simple, if there are a lot of such problems in the program, then you do not have to write this solution in every place, so it is too troublesome, the exception is used.

  if (index>i.length) {            throw new indexoutofboundsexception ();        }

hand it over to the back to deal with.


1) Catching exceptions

Method throws an exception, the method ends in the process of throwing the exception, and if you do not want the method to end, you can use a try block to catch the exception. This will not use each method to add error-checking code, to catch them together, for the same exception once resolved.

try{            }catch (xx) {            }catch (xx) {}

Once there is an exception of the same type, it is processed into the catch statement.



2) Create a custom exception

public class MyException {public    void F () {        System.out.println ("f () throw simple exception!");        try {            throw new simpleexception ();        } catch (Simpleexception e) {            //TODO auto-generated catch block            E.pri Ntstacktrace ();        }    }    public static void Main (string[] args) {        myexception me = new MyException ();        Me.f ();    }}

This example has many things to say, first of all, if you use the
throw new Simpleexception ();
then, add try and catch as above.

Or, throw directly in the method:

    public void F () throws simpleexception{        System.out.println ("f () throw simple exception!");            throw new Simpleexception ();    }
But when this is thrown directly,
ME.F ();
There is a problem, because the exception is thrown, or you continue to throw in the Main method:

    public static void Main (string[] args) throws simpleexception {        myexception me = new MyException ();        Me.f ();    }

Either you catch the exception in the main method to handle it:

public static void Main (string[] args) {        myexception me = new MyException ();        try {            me.f ();        } catch (Simpleexception e) {            System.err.println ("Catch it!");        }    }
The err output is the standard error stream, the out output is standard output, and the err is displayed in red font in the console, which is more noticeable.

But you will find that the output is catch it! Then is the F () throw simple exception. I'll mention that later.

        try {            me.f ();        } catch (Simpleexception e) {            e.printstacktrace (System.out);        } Result:son. Simpleexception at son. MYEXCEPTION.F (Myexception.java:8) at son. Myexception.main (myexception.java:13)
printstacktrace (), stack trace, prints from the method call until the exception is thrown, the default without parameters will be output to the standard error stream.


3) Record log

In fact, large-scale web site, every day has a record log, where there are errors to go to the log to find, what happened to the problem.

public class Loggingexception extends exception{    private static Logger Logger = Logger.getlogger ("Loggingexception" );    Public loggingexception () {        StringWriter sw = new StringWriter ();        Printstacktrace (new PrintWriter (SW));        Logger.severe (Sw.tostring ());    }    public static void Main (string[] args) {        try {            throw new Loggingexception ()        } catch (Loggingexception e) {
   system.err.println ("Catch" +e);}}}    Result: September 10, 2014 7:35:50 afternoon son. Loggingexception <init> grave: Son. Loggingexception at son. Loggingexception.main (loggingexception.java:16) catch son. Loggingexception
new PrintWriter (SW) extracts the output to a string.
PrintWriter the words as arguments in, back IO time to understand.
Logger,a Logger object is used to log messages for A specific system
or application component.

Serve method, Log a SEVERE message.


4) Exception Description

Java encourages the client programmer who uses this method to tell the exception that the method might throw. If there is source code, then the client programmer can find out the thrown exception by looking for the throw statement. However, the source code is not generally available.


Java provides the appropriate syntax, the book is very interesting, said in a polite way to tell the client programmer a method may throw the exception type, they can do the appropriate processing, which is the exception description.

In fact, the above mentioned throws without the use of try,catch.


5) Printstacktrace

I previously translated into the stack tracking, the book is written on the stack trajectory, in fact, the method returned is the stack trace elements of the array, 0 is the top element of the stack, advanced out, this is the characteristics of the stack.

public class Testelement {    static void First () {        try {            throw new Exception ();        } catch (Exception e) {            / /stack element  Gets the method name for            (stacktraceelement s:e.getstacktrace ()) {                System.out.println (S.getmethodname ());}        }    }    static void Second () {First ();}    static void third () {second ();}    public static void Main (string[] args) {first        ();        System.out.println ("////////////////");        Second ();        System.out.println ("////////////////");        Third ();    }} Result:firstmain////////////////firstsecondmain////////////////firstsecondthirdmain

Information for the entire stack element can be displayed individually.


This article first explains the basic concept of anomalies, to clarify why the use of abnormal ideas, the next article, about Try,catch nested this more depth of content, more exciting!


Java Programming Idea (ix)--Pass Exception handling error (1)

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.