Summary of Java Exceptions

Source: Internet
Author: User
Tags finally block stack trace

1, Exception Overview:
What is an exception?
An exception is a class that describes the abnormal behavior that occurs when a program runs.
The origin of the exception:
The anomaly originates from the description of the problem in real life, the problem in real life is also a thing, and the problem has many attributes and behaviors, such as problem name,
Problem information, problem cause, problem situation, etc. So the problem can also be described and encapsulated into objects. And real life has a lot of specific problems,
There are similarities and differences between these problems, so the upward extraction will form a system.
A system in Java that describes real-life problems:
Object
|--throwable
|---Error
|----OutOfMemoryError,.. Error,...
|---Exception
|----RuntimeException,...
|-----indexoutofboundsexception,nullpointerexception,aritchmeticexception,...
|------arrayindexoutofboundsexception,...

Overall: Trowable is an ancestor, divided into two major factions: Error and exception
Error: Used to describe a serious problem, the so-called serious problem is that do not need to deal with the problem of the targeted, because very serious, so directly
Program to stop, do not continue to execute is the general way of handling, do not need to deal with the problem, and then continue to ship
The line program.
Exception: Used to describe non-serious problems, such problems generally need to be targeted processing, that is, programmers need to be in the program code processing,
If given to the JVM, the JVM will simply stop the program and then throw the exception object (that is, the object that encapsulates the problem that occurred).
The general format for processing is:
Try{may be problematic, that is, the code snippet that throws the exception object}
catch (Exception class variable name) {The specified exception within () is targeted for processing}
Finally{the part that needs to be executed regardless of whether the exception is thrown or not
Note: Both the exception and the error classes have a number of subclasses that, when named, will make the last part of their name the parent class's
Name, which is either exception or error.

In learning the system, you need to look at the Java API Help documentation and learn to use the following principles: View the parent class definition and create the subclass object.

Note: Exceptions in the program are generated when the program is run, and the exception is generated in the form of an exception object, and the exception object is generated
There are two, one is automatically generated, one is manually generated, manually generated as "throw new Exception class name ();", with the generation of ordinary class
object, it just needs to be thrown manually with the keyword throw.
And once the exception object is thrown, the program will jump, that is, no longer execute the exception object to throw the following statement of the other code, jump
To the previous caller, and throws the exception object to the previous caller at the same time. If the upper caller does not handle it appropriately, it continues to throw
To the last caller until the top-level caller, JVM,JVM, defaults to the thrown exception, which is called the default
The exception handling mechanism is processed by default (in effect, the stack trace information of the exception object is printed, that is, E.printstacktrace ().
)。 Then end the entire program.
Typically, the caller throws the exception object to the caller, which is handled in two ways, one that is not handled and continues to
The upper caller is thrown, and the other is handled with a try...catch statement.

2, Try-catch:try. Catch.. They are a whole. There can be no finally block.
Try{may be problematic, that is, the code snippet that throws the exception object}
catch (Exception class variable name) {The specified exception within () is targeted for processing}
Finally{the part that needs to be executed regardless of whether the exception is thrown or not
The try code block is used to detect if an exception object is thrown, and catch is used to catch the thrown exception object.
There can be more than one catch block, and when there are multiple catch blocks, the exception class reference in () is matched in turn to see if the thrown exception object can be
To the exception class type shown in (), that is, "Exception object Instanceof Exception class" If the exception object (temporarily recorded as ex) can
To the E in the catch bracket (), execute the code in the catch brace {}, and then continue executing the TRY: Catch.. Finally in the
finally{}, continue executing the following code when you are finished executing the statement. The other catch blocks are no longer executed. If it cannot be assigned to E, continue
Attempts to assign a value to E in the next catch block until the match is correct or the match ends, and if the match end still does not match the appropriate E, the default
Continue to throw at the top.
When an auto-thrown exception object occurs, the exception is thrown to the previous caller, and the previous caller does not handle it or
The exception is not caught with a catch, and the exception continues to be thrown to the previous caller until it is processed by the JVM, in which case a sequential jump occurs.

Try
{
int a=3,b=0;
int x = A/b;
System.out.println ("x =" +x);
}
catch (ArithmeticException e)
{
System.out.println (e.tostring ())
}
catch (NullPointerException e)
{
System.out.println (e.tostring ())
}
Finally
{
}
Note: If no exception is thrown and no exception object appears in the try block, the statements in the try block are executed normally without executing the objects in the catch block.
Statement, if there is a finally block, execute the finally block, and then continue executing the other statement.

3. Exception declaration throws:
Exception declaration: Exception declaration refers to a method, for its own function statements will produce an exception is not certain, this time, can be in the back of the method header
Use the keyword throws to declare the type of exception object that may be produced (that is, the class to which it belongs).

Purpose: The exception declaration is used to tell the caller that this function may throw some exceptions for some reason, the caller needs to be prepared for the appropriate
action (or continue to throw an exception, that is, the caller also declares an exception in the function header, or uses a try: Catch.. The statement handles the exception).
and once a method has an exception declaration, its caller must use try: Catch.. Handle the exception object that may be thrown (that is, use the try block to detect
The calling portion of the method that may throw an exception), or continue to throw an exception (that is, also an exception declaration).

Special case: When an exception object is manually thrown within a function, the throw new Exception Class (), then the function needs to be declared with the exception class
, that is, with the throws exception class, placed between the () and {} of the function. This is mandatory, otherwise the compilation will error. In this case, only
is constrained for compile-time exceptions, and there is no constraint on the run-time exception (that is, RuntimeException and its subclasses), which is described in detail in 7.

eg.
Class B
{
public void method (int a,int B) throws Xxexception,yyexception
{
if (B = = 1)
throw new XX Exception ();
if (a < b)
throw new Yyexception;
return a*b;
}
}
Class A
{
public static void main ()
{
b b = new B ();
try//defines the variable in which the local variable is valid only in the try code block. So pay attention to the scope of the variable.
{
int x =b.method (3,1);
SYSTEM.OUT.PRINTLN (x);
}
catch (Xxexception e)//the definition here is similar to a function, E is a local variable and only valid in that catch block.
{
System.out.println (XX);
}
catch (yyexception e)//These code blocks can have various statements that define many things, inner classes, variables, and objects.
{
System.out.println (YY);
}
System.out.println ("over!");
}
}

4, multi-exception processing: When a try block corresponds to multiple catch blocks, that is, when there are multiple exception objects to be processed, the exception object should be handled according to the following rules:
The exception object of the parent class is placed below the exception object of the subclass. Otherwise the compilation will error, because the subclass exception object processing code is always
cannot be performed.
At the same time, a method can throw multiple exception objects, but only one exception object at a time, not throwing two exception objects at a time
, the method can be a declaration of multiple exception classes, separated by commas, that is, throws Xxexception,yyexception,zzexception
5. Custom Exceptions:
Custom Exception Requirements: When there are problems that are specific to this project in your project, it is not described in Java, so you need to
The problem is described, which is the need to customize your own exception class.
Custom exception: A class needs to be added to the Java exception System in order to become a custom exception class. Generally by inheriting the exception class or
RuntimeException class to complete. This custom exception class can override the methods in the parent class, or you can define your own unique data and
Members.
What about inheriting exception or runtimeexception?
If the custom exception class is a compile-time exception, the exception class is inherited.
If the custom exception class is a run-time exception, the RuntimeException class is inherited.
How to tell if a custom exception class is a compile-time exception, see 7.
6, the difference between throw and throws:
The throws keyword is used on a function to declare an exception class. It is followed by the exception class name, can be followed by multiple, separated by commas
The Throw keyword is used within a function to throw an exception object. It is followed by an exception class object, only one.

7, RuntimeException:
What are run-time exceptions and compile-time exceptions?
There are two kinds of exceptions, one is a compile-time exception and one is a run-time exception.
A compile-time exception is an exception that is detected at compile time, which means that when the exception object appears, it does not completely affect the operation and finishes processing the
After the exception, you can still continue to run the program.

A run-time exception is an exception that is not detected at compile time, which means that the delegate cannot perform the operation when the exception object appears, so the
The exception object represents an operation that cannot be performed, so which of the following statements may be based on the operation should not continue to run.
The entire program should not continue to run, the code should be revised to achieve the correct operation of the purpose. So when it comes up
When this exception occurs, the JVM expects the program to terminate and stop running, and if the class is unhandled, the program continues to run
is the equivalent of hiding the situation, so that we do not know what the program appears to be the problem, if it is an operation problem, it should stop execution
, fix the code. For example, null pointer exception (nullpointerexception), arithmetic exception (ArithmeticException) divisor is
0. This indicates that there is a problem with the invocation, and that there is no correct argument for the correct operation, and the code needs to be corrected.

Compile-time exception, when the exception occurs in the program, the program will continue to execute after the targeted processing.
Run-time exception, is in the program when the exception, I want to not handle the exception, hope that the program to stop, so that the programmer to find the problem,
and make code modifications.

Therefore: if there are thrown compile-time exception objects within a function, the declaration of the exception class must be made on the function. Otherwise, the compilation fails, and
The caller must be handled by the appropriate action (continue to throw or try processing), or the compilation will be faulted.
If you have thrown a run-time exception object inside a function, you do not have to declare the exception class on the function (declaring compilation is also true, but generally
Not declared), the caller does not have to do the processing (the operation is also right, but generally does not operate), the same as the compiler will pass. While the run-time
The exception class refers to RuntimeException and its subclasses.

*/


Class Demo
{
int x = 0;
int div (int a,int b)
{
int[] arr = new INT[5];
System.out.println (Arr[a]);
return a/b;
}
void Print (String str) throws Arithmeticexception,nullpointerexception
{
Try
{
if (Str.equals ("Wanglinlin"))
{
String info = "failure! did not catch the exception thrown by--div--";
Try
{
System.out.println (Str+div (4,0));
}
catch (ArithmeticException e)
{
info = "Success! successfully captures the exception thrown by--div--";
System.out.println (E.getmessage ());
}
Finally
{
System.out.println ("Print Finally:" +info);
}

}
}
catch (NullPointerException e)
{
System.out.println (E.getmessage ());
}

}
}


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 (NullPointerException E)//here corresponds to polymorphic Exception e = new ArithmeticException ();
{
System.out.println ("divisor is 0");
System.out.println (E.tostring ());//This statement, like System.out.println (e), prints an object that the system automatically calls
ToString () to output the string representation of the object.
}
finally//a finally block of code that executes regardless of whether an exception is thrown, and whether the exception is caught by a catch block.
{
System.out.println ("finally!");
}
System.out.println ("over!"); /Only if there is no exception, the correct execution and an exception occur and the exception is caught by the catch block.
Executes the statement, which is not executed when an exception occurs, and the catch code block does not catch an exception.
Jumps directly to the upper-level caller and throws the exception to the upper-level caller after the finally statement is executed.
}
}

Summary of Java Exceptions

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.