JAVA Advanced exception

Source: Internet
Author: User
Tags throw exception

Exceptions: Program exception events that occur due to hardware device problems, software design errors, and so on during operation.
There is no perfect program in the world. There are always various problems in the procedure. Therefore, it is necessary to add an error handling mechanism to the program. It's like a lot of public places need to have a fire-proof security system for a reason.

Catching exceptions

Exception handling format

Try{
//statements that may have an exception
}Catch(Type1 E1) {
//exception type 1 handling code
}Catch(Type2 E2) {
//Exception type 2 handling code
}
// etc...
Catch(Typen en) {
//exception type N processing code
}finally{
//The finally statement block is executed whether or not an exception occurs
//In the try...catch exception handling mechanism, the FINALLY keyword is optional
}

The block after the try keyword is the monitoring area of the exception .

The block after multiple catch keywords is the appropriate handler for each exception to be caught.

The block after the finally keyword is always executed , whether or not an exception occurs. The finally keyword is not required in the Try...catch mechanism.

PublicclassExceptionDemo02 {
PublicStaticvoidMain (String args[]) {
SYSTEM.OUT.PRINTLN ("********** calculation begins ***********");
inti = 10;
intj = 0;
Try{
inttemp = i/j;//An exception is generated here
SYSTEM.OUT.PRINTLN (the result of dividing two numbers: "+ temp);
System.out.println ("****************************");
}Catch(ArithmeticException e) {
System.out.println ("An exception has occurred:" + e);
}finally{
System.out.println ("Right and wrong, I am here, do not shift");
}
SYSTEM.OUT.PRINTLN ("********** calculation End ***********");
}
};Sample Code



Custom Exceptions

Although Java provides a large number of exception classes, it is not possible to foresee all exceptions. You can define the exception class yourself to represent specific problems that your program may encounter.

To customize an exception class, you must inherit from an existing exception class, preferably with a functionally similar exception class inheritance.

//Custom exception classes, inheriting the exception class
classMyExceptionextendsException {
PublicMyException (String msg) {
Super(msg);//call a constructor that has a parameter in the exception class, passing the error message
}
};

Publicclassdefaultexception {
PublicStaticvoidMain (String args[]) {
Try{
ThrowNewMyException ("Custom exception. ");//Throw Exception
}Catch(Exception e) {
E.printstacktrace ();
}
}/*Output:
MyException: Custom Exception.
At Defaultexception.main (defaultexception.java:11)
*/
}



Throw Exception

When defining a method, you can use the throws keyword declaration, which uses the throws declaration method to indicate that this method does not handle the exception, and that it is handled at the call of the method.

PublicReturn value type method name (parameter list ...)throwsException class {}

It is important to note that if the exception class type is not a run-time exception type, you must use Try...catch for exception capture and processing when calling this method, regardless of whether there is a problem.

classDiv {
//defines the division operation, and if there is an exception, it is handed to the manipulated
PublicintDivintIintJthrowsException {
inttemp = i/j;
returnTemp
}
};

PublicclassThrowsDemo01 {
PublicStaticvoidMain (String args[]) {
div div =NewDiv ();
//Div.div (ten, 0);//If you do not use the try...catch structure, the compiler will consider an error
Try{
SYSTEM.OUT.PRINTLN ("Division operation:" + div.div (10, 0));
}Catch(Exception e) {
E.printstacktrace ();//Printing Exceptions
}
}
};Sample Code

Unlike throws , thethrow keyword indicates that an exception is thrown actively, throwing an instantiated object that throws the exception class directly.

Publicclassthrowdemo01{
PublicStaticvoidMain (String args[]) {
Try{
ThrowNewException ("Throw yourself at the game." ") ;//an instantiated object that throws an exception
}Catch(Exception e) {
System.out.println (e);
}
}
};Sample Code


type of Exception

All exception classes in Java inherit from the Throwable class.

Exceptions can be divided into two main categories: Exception and Error.

Exception: Generally refers to the problem that occurs in the program, can be handled by Try...catch.

Error: This is usually a JVM error and the program cannot handle it.

Exception can also continue to be subdivided into run-time exceptions (RuntimeException) and non-runtime exceptions .

Run-time exceptions can be handled without using try...catch.

non-run-time exceptions must useTry...catch for processing.

Take a look at the following code:

PublicclassRuntimeExceptionDemo01 {
PublicStaticvoidMain (String args[]) {
intresult = 0;
String str = "10";
String str2 = "abc";
result = Integer.parseint (str);//Convert a number in a string to an int type
SYSTEM.OUT.PRINTLN (Result * result);
result = Integer.parseint (STR2);//An exception occurs when you try to convert a letter in a string to an int type
SYSTEM.OUT.PRINTLN (Result * result);
}
};

When you execute the above code, an exception occurs when you call Integer.parsein () a second time. Let's take a look at the definition of this method:

PublicStaticintparseint (String s)throwsNumberFormatException

The throws keyword is used here, but no try...catch is used when the actual call is made, and the compiler does not have an error.

This is because all classes that inherit from runtimeexception can be processed without using Try...catch. In this case, if an exception is generated, it will be processed by the JVM , which will certainly break the program.

Therefore, if you want the program to continue executing in the event of an error, it is best to use the Try...catch exception handling mechanism.



References

"Thinking in Java"

"Java Development Practical Treasure"

JAVA Advanced exception

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.