Exception Handling for Java Basics (v)

Source: Internet
Author: User

Run-time errors, non-compilation errors, and the most important to observe the name and line number of the error.

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 execution of the program (for example, except for a 0 overflow, where the table is out of bounds and the file being read does not exist).

Why do I need to handle exceptions?

When an exception occurs, the program is blocked from running and may not be able to know the cause of the interruption or produce unpredictable results. A well-designed program should provide a way to handle these errors when an exception occurs.

Exception Handling Process:

Defining a procedure-declaring an exception: declaring that the method might throw an exception, throws the exception class name.

Define procedure-Throws an exception: sets the condition to judge, satisfies the condition, constructs and throws the exception object, the throw new Exception class constructs the method.

Call procedure-Throw exception (throw): An exception event occurs during the execution of a Java program and can generate an exception class object that encapsulates the information of the exception event and will be submitted to the Java runtime System.

Catch exception (catch): 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.

Exception class: Foundation Class: Throwable, Subclass: Error,exception,runtimeexception.

Error: Called a bug, generated and thrown by a Java virtual machine, including dynamic link failure, virtual machine error, and so on, the program does not handle it.

Exception: The parent class of all exception classes whose subclasses correspond to a variety of possible exception events, typically requiring the user to display a declaration or capture.

RuntimeException: A special kind of exception, such as by 0, array subscript out of bounds, it produces more frequent, processing trouble, if the display of the declaration or capture will have a significant impact on program readability and operational efficiency, so the system automatically detects and gives them to the default exception handlers, Users do not have to handle it.

Exception capture and Handling: try{contains code that can produce exceptions}catch (Exception class name variable name) {Exception handling code}finally{is executed regardless of whether an exception occurs},try code snippet followed by one or more catch code snippets. If no exception is generated, all the catch code snippets are skipped and not executed.

The exception object encapsulates information about the occurrence of an exception event, and some methods of the exception object can be used in the CATCH statement block to obtain the exception information. Like what:

The GetMessage () method is used to obtain information about the exception event.

The Printstacktrace () method is used to track the contents of the execution stack when an exception event occurs.

The finally statement provides a unified exit for exception handling, which enables unified management of the program's state before the control process is transferred to other parts of the program. It is usually possible to clean up resources in a finally statement: Close the open file, delete the temporary file, and close the database connection.

For example, a file input stream that reads one character at a time, receives it using an int type variable, and prints it out. The input file is placed by default in the project root directory with the following code:

Import Java.io.FileInputStream;

Import java.io.IOException;


public class Testexceptioncatch {


public static void Main (string[] args) {

TODO auto-generated Method Stub

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 ());

E.printstacktrace ();

}finally{

Try

{

if (in!=null)

{

In.close ();

}

}

catch (IOException E)

{

throw new RuntimeException ("Shutdown failed");

}


}


}


}

Principle:

1. If a try statement block, the capture statement of the base class exception is written on top of the subclass exception capture statement, a compilation error is reported. That is, the subclass exception must be written before the base class exception is handled, and when the class exception occurs, the exception is caught and handled by the subclass, and the base class exception is not processed, that is, the base class catch block code is not executed.

2. The overriding method needs to throw an exception that is consistent with the type of exception thrown by the original method or does not throw an exception.




This article is from the "one step, one step" blog, please be sure to keep this source http://summerflowers.blog.51cto.com/5202033/1920446

Exception Handling for Java Basics (v)

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.