Exception handling
An exception is the name and line number of the error that occurs during a run.
Arrayindexoutofbound
The so-called error refers to some of the abnormal events that occur during program operation (except 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 errors when an exception occurs, so that the program does not block or produce unpredictable results due to the occurrence of an exception
During the execution of a Java program, you can generate an exception class object that encapsulates the information of the exception event and will be presented to the Java Runtime System, which is called a throw exception, and when the Java Runtime system receives the exception object. Will look for code that can handle this exception and hand the current exception object to its handling, a process called catch exception
try{...} catch (Arithmathicexception e) {...}
public void SomeMethod () throws someexception{ //declares that the method may throw an exception
if (Somecondition ()) {
throw new Someexception (""); Constructs and throws an exception object
}
}
try{
SomeMethod ();
}catch (Someexception e) {
Exception handling code
}
Exception class Throwable:error (error not handled), Exception (exception that can be handled) (RuntimeException, other Exception)
The parent class of the Exception exception class typically requires the user to display the declaration or capture
The code in finally is eventually executed, and the cleanup of resources is typically done in the Finally statement: Close open files, delete temporary files
Printstacktrace () method to track the contents of the execution stack when an exception event occurs
The GetMessage () method, which is used to obtain information about the exception event
void m (int i) throws arithmeticexception{
if (i==0) throw new ArithmeticException ("Dividend cannot be 0");}
Using custom exceptions generally has the following steps:
1. Declaring your own exception class by inheriting the Java.lang.Exception class
2. Generate an instance of the custom exception in the appropriate location of the method and throw it with the throw statement
3. Declare the exception that may be thrown by the method in the declaration section of the method with the throws statement
Class MyException extends exception{
private int id;
Public MyException (String)
Horse Soldier Java Tutorial Note 3