Java Learning data-java exception handling

Source: Internet
Author: User
Tags throw exception throwable

4. Java Exception handling

4.1 Java Exception Concepts

Java Exceptions are a mechanism provided by Java for handling errors in a program.

the so-called error refers to some unusual events that occur during the running of the program (for example: except for 0 overflow, array subscript out of bounds, the file to be read does not exist).

A well-designed program should provide a way to handle these dislocations when an exception occurs, so that the program does not block or produce unforeseen results because of an exception.

during the execution of a Java program, such as an exception event, you can generate an exception class that encapsulates the information of the exception event and will be presented to the Java runtime's system, a process called throw (throw) exception.

When the Java Runtime system receives an exception object, it looks for code that can handle the exception and hands the current exception object to its processing, a process known as catch (Catch) exception.

4.2 Exception types

Throwable

Error Exception (IOException, RuntimeException)

4.3 Built-in exceptions for Java

In addition to exception handling defined in the Java.lang package, exceptions are handled in other Java packages. In fact, almost every Java package has a corresponding exception class to handle the corresponding exception, but the runtimeexception exception and its derived subclasses are not processed, how many exceptions derived from RuntimeException can be automatically called. Note: We can use catch to catch exceptions when we are dealing with exceptions, that is, if the system finds an exception during the run, it will be captured for human processing, or thrown to throw an exception, that is, during the run, a statement has an exception, such as the file cannot be found, The system automatically throws the exception and continues to run the program down. These two ways are different, by catching the exception we can more clearly understand the program running in the exception, so that we better improve, throw exception can guarantee the normal operation of the program. But here is to remind you still choose catch exception, so if the software later have any bug or processing. To give you an example, like our ATM machine, if we have an exception in the process of taking money, we certainly want the system to throw an exception so that we can reflect the situation to the bank to solve the problem we are experiencing, which is one of the benefits of catch exception. At the same time, if the exception is thrown, the system throws a lot of professional terminology, so what users think, you can imagine, if a person to collect money, suddenly on the screen shows a lot of our Java language throws an exception when the professional terminology, this will think. So, with catch exceptions, we can modify the exception prompt so that the user is better able to understand it. Let's take the money for example, if we choose the program throws an exception, if a person to fetch money, suddenly the program run an exception, but this exception is thrown, but now the problem is thrown after unknowingly your bank card balance becomes less what would you think. Therefore, we recommend that you try to choose the catch exception when you write the program.

4.4 Java Exception Examples

Import java.io.*;


public class TestEx {

public static void Main (string[] args) {

try {

System.out.println (2/0);

} catch (ArithmeticException ae) {//its own defined Exception class object name, the system passes the exception object to AE, AE equivalent to the formal parameter

System.out.println ("error");

ae.printstacktrace ();///Common approach: Print out the wrong stack information! The system defaults to the stack information that is printed incorrectly.

}

}

}

Operation Result:

Something went wrong.

Java.lang.ArithmeticException:/By zero

at Testex.main (testex.java:7)


4.5 Exception capture and handling

In the Java language exception handling mechanism includes exception capture and exception handling two parts. With exception handling, we can handle the caught exception artificially, and of course it can be handled in a corresponding way.

the format for capturing and handling exception statements is as follows:

try {...;} //statement that could throw an exception

catch (Exception1 E1) {...;} To handle an exception

catch (Exception2 E2) {...;}

......

finally {...}//the executing program body before the end of exception handling

4.6 Exception throws

4.6.1 Throw statement

In the Java language, the throw statement actively generates an exception, throws an exception when the program executes to the throw statement, and then moves the control to a corresponding catch block. If there is no catch module in the current method, then the Java Virtual Machine transfers control to the catch code block in the previous method that called the method, if there is no catch module in the method, The Java Virtual machine will continue to pass control up the call stack of the method until it finds a catch module that can handle the exception. The general form of the throw throw exception statement is:

throw new Exception ("The program just, throw an Exception");

4.6.2 throws statements

The throws keyword is used in a method declaration to list any exceptions emitted from the method, not originating from the error or runtime exception (exceptions derived from the Runtimeexeeption type are usually avoidable types, Exceptions derived from the error type are usually related to serious system problems. The method that can actively throw an exception must be declared with throws. A method that typically contains a throws clause is declared as:

type method_name (parameter_list) throws exception_list{}

where exception_list is a comma-delimited list of exceptions that the method can throw.

4.6.3 finally statement

The Finally keyword is the module immediately following the Try/catch exception module. Because sometimes we want to execute a piece of code, but before we execute the code, an exception occurs, and if an exception occurs, the code is not executed, but we want to execute the code, so we use the Finally keyword. When using the Finally keyword, the finally statement must be executed once, regardless of how the previous try statement and catch statement are executed and executed. So, we put the code we want to execute in the finally module to ensure that even if an exception occurs.

4.7 Custom Exception Classes

Although there is a very powerful exception handling class in Java, we have to deal with some special exceptions by ourselves, so we need to customize the exception class. The method of creating an exception class is simple, as long as you define a subclass of exception to be implemented. Because exception inherits from Throwable, custom exception classes can obtain the methods defined in the Throwable class, and some methods inherited from the Throwable class can be overloaded in custom classes, of course.

4.8 Additional issues with exception application

You must catch smaller exceptions before you catch large ones.

using custom usually has the following steps:

A) declare your own exception class by inheriting the Java.lang.Exception class.

b) generate an instance of the custom exception at the appropriate location of the method and throw it with a throw statement.

c) declaring the method with the throws statement in the declaration section of the method may throw an exception.

Exception Consistency: The overriding method needs to throw a consistent exception or no exception that is thrown by the exception type that the member method throws.

4.9 Exception Application Examples:

Import java.io.*;


public class TestEx {

public static void Main (string[] args) {

FileInputStream in = null;

try {

in = new FileInputStream ("MyFile.txt");

int b;

B = in.read ();

while (b! =-1) {

System.out.print ((char) b);

B = in.read ();

}

} catch (IOException e) {

System.out.println (E.getmessage ());

/*

*} catch (FileNotFoundException e) {e.printstacktrace ();

*/

} finally {

try {

in.close ();

} catch (IOException e) {

e.printstacktrace ();

}

}

}

}

Operation Result:

MyFile.txt (the system cannot find the file specified.) )

Exception in thread "main" java.lang.NullPointerException

at Testex.main (testex.java:20)


Java Learning data-java exception handling

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.