Concepts and classifications of Java exceptions

Source: Internet
Author: User

Java exceptions are a mechanism provided by java to handle errors in programs.
The so-called error refers to some abnormal events that occur during the running of the Program (for example, in addition to 0 overflow, the array subscript is out of bounds, and the file to be read does not exist ).
A well-designed program should provide methods to handle these errors when a program exception occurs so that the program will not block or generate unforeseen results due to the exception.
If an exception occurs during Java program execution, an exception class object can be generated. The exception object encapsulates information about the exception event and is submitted to the java runtime system, this process is called throw exceptions.
When the system receives an exception object during Java runtime, it looks for code that can handle this exception and submits the current exception object to it for processing. This process is called catch exception.

In try, an incorrect statement may occur, and in catch, measures taken after an exception occurs.

Exception category:
Error: An Error is generated and thrown by the Java Virtual Machine, including dynamic link failure and virtual machine Error. The program will not process it.
Exception: the parent class of all Exception classes. Its subclass corresponds to a variety of possible Exception events, which generally need to be declared or captured by the user.
Runtime Exception: a special type of Exception, such as Division by 0 and array subscript out-of-range. It is frequently generated and troublesome to handle, if the declaration or capture is displayed, the program readability and running efficiency will be greatly affected. Therefore, the system automatically detects and delivers them to the default exception handler (you do not have to handle it ).

 
In fact, the exception mainly involves five keywords: try, catch, finally, throw, and throws.
Try statement:
Try {......} The statement creates a piece of code, which is the scope of a distribution and processing exceptions. During execution, the code segment may generate and throw one or more types of exception objects. The catch statements following the segment must handle these exceptions respectively. If no exception occurs, all catch code segments are skipped.
Catch statement:
The catch Block is the code that processes exceptions. Each try block can be accompanied by one or more catch statements to process different types of exception objects that may be generated.
The catch (SomeException e) object declared in catch encapsulates the information about an exception event. In the catch statement block, you can use some methods of this object to obtain this information.
For example, the getMessage () method is used to obtain information about an exception event.
The printStackTrace () method is used to trace the stack content when an exception event occurs.
Finally statement:
Finally statements provide a uniform exit for exception handling, so that the state of the program can be managed uniformly before the control process is transferred to other parts of the program.
No matter whether exceptions are thrown in the program block specified by try, the Code specified by finally must be executed.
You can usually clear resources in finally statements, such:
1. Close open files
2. Delete temporary files
3 .......
The difference between throw and throws:
1. The throws keyword is usually used to specify exceptions that may be thrown when the method is declared. Multiple exceptions can be separated by commas. When this method is called in a function, if an exception occurs, the exception is thrown to the specified exception object.
For example:
[Java]
<Span style = "font-size: 18px;"> public class test {
Static void pop () throws NegativeArraySizeException {
// Define the method and throw the NegativeArraySizeException
Int [] arr = new int [-3]; // create an array
}
Public static void main (String [] args) // master Method
{
Try {
Pop (); // call the pop () method
} Catch (NegativeArraySizeException e ){
System. out. println ("exception thrown by the pop () method"); // output exception information
}
}
} </Span>
2. The throw keyword is usually used in the method body and an exception object is thrown. The program stops immediately when the throw statement is executed, and the subsequent statements are not executed. After throw throws an exception, if you want to capture and handle the exception in the code above, you must use the throws keyword in the method that throws the exception to specify the exception to be thrown; if you want to catch the exception thrown by throw, you must use the try {} catch {} statement.
For example:
[Java]
<Span style = "font-size: 18px;"> public class MyException extends Exception {// create a custom Exception class
String message; // defines a String-type variable.
Public MyException (String ErrorMessage) {// parent class Method
Message = ErrorMessage;
}
Public String getMessage () // overwrite the getMessage () method
{
Return message;
}
}
 
 
Public class Captor {// create a class
Static int quotient (int x, int y) throws MyException {
If (y <0) {// determines whether the parameter is smaller than 0
Throw new MyException ("divisor cannot make negative number"); // exception information
}
Return x/y; // return Value
}

Public static void main (String [] args) // master Method
{
Try {
Int result = quotient (3,-1 );
} Catch (MyException e) {// handle custom exceptions
System. out. println (e. getMessage (); // output exception information
} Catch (ArithmeticException e ){
// Output ArithmeticException arithmetic exception
System. out. println ("the divisor cannot be 0"); // output the prompt message.
} Catch (Exception e) {// handle other exceptions
System. out. println ("Other exceptions occurred in the program ");
}
}
} </Span>

Other exceptions:


Note: The gray part is the printed stack error message.
 
Declare and throw an exception:
The rewrite method must throw an exception of the same type as the exception thrown by the original method or not.


 
Custom exception:
To use a custom exception, follow these steps:
1. Declare your own Exception class by inheriting the java. lang. Exception class.
2. generate an instance with a custom exception at an appropriate position in the method and throw it with the throw statement.
3. Use the throws statement to declare the exceptions that may be thrown by the method.
 

 

 
Exception summary:
1. A Graph
2. Five keywords
3. Capture small exceptions first.
4. Relationship between exceptions and rewriting


Related Article

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.