Black Horse Programmer —————— > Exception handling throws

Source: Internet
Author: User

-------Android Training, Java training, look forward to communicating with you! ----------

Java exceptions are categorized into two major classes, checked exceptions and runtime exceptions (runtime Exceptions). All instances of the RuntimeException class and its subclasses are called Runtime exceptions, and exception instances that are not runtimeexception classes and their subclasses are referred to as checked exceptions.

There are two ways to handle checked exceptions.

1: The current method explicitly knows how to handle the exception, the program should use the Try...catch block to catch the exception, and then fix the exception in the corresponding catch block.

2: The current method does not know how to handle this exception, it should be declared when the method is defined.

Runtime exception is more flexible, runtime exception does not need to explicitly declare thrown, if the program needs to catch runtime exception, you can also use Try...catch block to implement.

Throwing an exception using the throws declaration

The idea of throwing an exception using the throws declaration is that the current method does not know how to handle this type of exception, which should be handled by the caller at the top level, and if the main method does not know how to handle this type of exception, you can also use the throws declaration to throw an exception that will be passed to the JVM for processing. The JVM handles exceptions by printing the exception's trace stack information and terminating the program's operation.

Throws declaration throws can only be used in method signatures, throws can declare multiple exception classes, and multiple exception classes are separated by commas. Once the exception is thrown using the throws statement declaration, the program does not need to use the Try...catch block to catch the exception.

If a method with a throws declaration is called in a piece of code, the method declaration throws a checked exception, indicating that the method expects its callers to handle the exception. That is, when the method is called, either the exception is explicitly caught in the try block, or it is placed in another method with the throws declaration thrown. This usage is demonstrated in the following procedure.

1  Public classthrowstest2 {3 4      Public Static voidMain (string[] args)throwsException5     {    6         //because Test (); method declaration throws a IOException exception7         //so the code that calls the method is either in the Try...catch block or in another method with the throws declaration thrown. 8 test ();9 Ten     } One  A     Private Static voidTest ()throwsIOException -     {     -         //because the FileInputStream constructor declares that the IOException exception is thrown the         //so the code that calls IOException is either in Try...catch or in another method with the throws declaration thrown.  -FileInputStream FIS =NewFileInputStream ("A.txt"); -          -     } +  -}

There is a limitation when using the throws declaration to throw an exception, that is, a rule in "two small" when the method overrides: The subclass method declaration throws an exception type that is the subclass of the exception type thrown by the parent class method declaration, or the same exception that is thrown by the subclass method declaration that does not allow more exceptions than the parent class method declaration throws.

This shows that there are at least two major inconveniences in using checked anomalies.

1: For checked exceptions in the program, Java requires that the exception be explicitly caught and handled, or explicitly declared to be thrown. This increases the complexity of the programming.

2: If the checked exception is explicitly declared in a method, it will cause the method signature to be coupled to the exception, and if the method is to override the parent class, the exception thrown by the method will also be limited by the exception thrown by the overridden method.

The runtime exception is recommended for most of the time without using the checked exception. In particular, the runtime exception is more concise when the program needs to throw an exception on its own. When using the runtime exception, the program does not have to declare the throw checked exception in the method, and once a custom error occurs, the program throws the runtime exception.

Throw an exception with throw

Many times, if the system throws an exception, it may need to be determined according to the business requirements of the application, which is an exception if the data in the program does not match the established business requirements. Exceptions caused by inconsistent business requirements must be thrown by the programmer, and the system cannot throw such exceptions.

If you need to throw an exception yourself in the program, you should use the throw statement, which can be used alone, throw statements are not exception classes, but an exception instance, and only one exception instance can be thrown at a time.

If the exception thrown by the throw statement is a checked exception, the throw statement is either in the try block, explicitly capturing the exception, or in a method with the throws declaration thrown, which gives the caller of the method the exception to handle If the exception thrown by the throw statement is a runtime exception, the statement does not need to be placed in the try block or in a method thrown with a throw declaration, and the program can either explicitly use Try...catch to catch and handle the exception, or ignore the exception at all. The exception is given to the method caller for processing. For example, the following program.

 Public classThrowstest { Public Static voidMain (string[] args) {Try        {            //The call declares a method that throws a checked exception, either explicitly catching the exception, or declaring the thrown in the main method againThrowchecked (-3); }        Catch(Exception e) {System.out.println (E.getmessage ()); }            //invoking a method that throws a runtime exception can either explicitly catch the exception or ignore the exceptionThrowruntime (3); }    Private Static voidThrowchecked (intAthrowsException {if(A > 0)        {            //self-throwing exception exception//the code must be in a try block, or in a method with a throws declaration            Throw NewException ("A has a value greater than 0, does not meet the requirements"); }                }        Private Static voidThrowruntime (inta) {if(A > 0)        {            //self-throwing runtimeexception exception, which can be explicitly caught by the exception//You can also ignore the exception completely and give the method caller the exception to handle            Throw NewRuntimeException ("A has a value greater than 0, does not meet the requirements"); }            }    }

Custom exception Classes

In general, a program rarely throws a system exception on its own, because the class name of the exception usually contains useful information about the exception. So when you choose to throw an exception, you should choose the appropriate exception class so that you can clearly describe the exception, in which case the application often needs to throw a custom exception.

Custom exceptions should inherit the exception base class, and if you want to customize the runtime exception, you should inherit the RuntimeException base class. When defining an exception class, you typically need to provide two constructors: one is a parameterless constructor, and the other is a constructor with a string argument that will act as a description of the exception object (that is, the return value of the GetMessage () method of the Exception object)

The following program creates a custom exception class

 Public class extends exception{    // no parameter constructor public      auctionexception () {}        / / constructor with a string argument public      auctionexception (String msg)    {          Super(msg);}    }

Black Horse Programmer —————— > Exception handling throws

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.