Up posture: Java exception? Try custom Exceptions

Source: Internet
Author: User
Tags getmessage

1. Exceptions

In Java, each exception is an instance of a class named Throwable.

The try-catch-finally statement we used

    • Try

Try to execute the contents of the Try statement block, catch it if there is an exception, and execute the code in the CATCH statement block

    • Catch

In the parameters of the catch statement we define the specific exception type, but these specific exceptions are exception subclasses, so we can catch all exceptions by changing the parameter to exception e (but not recommended, or put the catch exception base class to the last, Because sometimes you need to do something different for different anomalies.

    • Finally

Finally "Last", the contents of the statement block will be executed at the end

    • Handling Exceptions

After catching the exception, we also need to deal with these exceptions, we can output these abnormal messages, or after the capture to throw another exception: Common message output is GetMessage () and Printstacktrace ()

2. Custom Exceptions

The exception type given by the official (JDK 8) is mostly not seen, ( shame )

It doesn't matter, we can define our own exceptions.

The specific exception is inherited from the exception class, so the exception we want to customize also needs to inherit the base class.

We customize the exception named MyException, we need to inherit the base class exception, and then we call the constructor of the base class with a parameter:

 Public class extends Exception {   public  myexception (String message) {       Super(message);}   } 

Then we test this exception because it is a test, so we throw the defined exception directly:

 Public class Test {    publicstaticvoid main (string[] args)throws  myexception {        try{            thrownew myexception ("Custom Exception");        } Catch (MyException e) {            System.out.println (e.getmessage ());     }}}

Print exception results

3. Viewing exception information

Sometimes we need to look at the exception information for debugging, and 3 ways to inherit from the Throwable base class are given in the JDK.

ToString () method

Before we talk about methods, let's look at the ToString () method covered in the Throwable class:

This means: the ToString () method returns a string representing the information for the Throwable instance (exception), in the following format: Object name: Localized information

Example:

Run out of results on the second line:

Java.io.FileNotFoundException:test.txt (the system cannot find the file specified.) ) at ...

Java.io.FileNotFoundException is an example of Throwable, Text.txt ... The following information is localized information, for different locations to give specific information, used for debugging can quickly locate

GetMessage ():
the detail message string of this Throwable instance (which may be null)将Throwable实例(通常所说的异常)的具体信息以String类型给出(可能不存在)
Printstacktrace ()

There are three types of this method: no parameter, with parameter PrintStream and with parameter PrintWriter

The Printstacktrace () method, which we normally use to view exception information, prints the parameter printstream (print output stream) directly on the console: the ability to output information through streams to other places,

Do a test:

ImportJava.io.*; Public classTest { Public Static voidMain (string[] args)throwsioexception{OutputStream out; Try{            Throw Newruntimeexception (); }Catch(RuntimeException e) {out=NewFileOutputStream ("C:\\users\\94545\\desktop\\test.txt"); //FileOutputStream as the output stream of the PrintStreamPrintStream PrintStream =NewPrintStream (out);            E.printstacktrace (PrintStream);            Out.close ();        Printstream.close (); }    }}

Print successfully

With parameter PrintWriter (character print output stream): Output information to other places
ImportJava.io.*; Public classTest { Public Static voidMain (string[] args)throwsexception{OutputStream out; Try{            Throw Newruntimeexception (); }Catch(RuntimeException e) {out=NewFileOutputStream ("C:\\users\\94545\\desktop\\test.txt"); PrintWriter PrintWriter=NewPrintWriter (out,true);            E.printstacktrace (PrintWriter);            Out.close ();        Printwriter.close (); }    }}

Print Success!

Extended

Do you know what the difference is between throw and throws?

For example, in method A, if you do not need to capture it immediately when an exception is generated, and then capture it when method B calls method A, add throws after the method name of a, and if you need to capture in method A, use the throw

So the difference between the two is actually where to deal with the anomaly

Summary

See who caught the exception and decide how you want to use it

The format of user input data is always correct, select Open file must exist, and will never appear bug--"Java Core technology Volume One"

Up posture: Java exception? Try custom Exceptions

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.