Miss Miao, huaqing Vision Embedded College lecturer.
Exception handling in Java is still more interesting! It is your control, not your management, it is best not to leapfrog the administration! Otherwise my level of management existence is meaningless!
Java exception handling is implemented by 5 keywords: try,catch,throw,throws,finally. Here I mainly talk about Throw,throws.
Throws statements
Throws always appears when a method declaration is used to indicate that the member method might throw an exception. If there are multiple exceptions, separate them with commas. For most exception subclasses, the Java compiler forces you to declare the type of exception thrown in a member function. If the types of exceptions are error or runtimeexception, or their subclasses, this rule does not work because this is not expected in the normal part of the program. If you want to explicitly throw a runtimeexception, you must declare its type with the throws statement.
Throw statement
The throw always appears in the method body and is used to throw an exception. The program terminates immediately after the throw statement, and the statement following it is not executed. After throwing an exception through throw, if you want to catch and handle the exception in the previous level of code, you need to use the throws keyword in the method declaration to indicate the exception to throw in the method declarations.
If a method displays an identity that throws an exception, you must use the Try-catch statement.
The following is an example of a custom exception class:
Class MyException extends Exception {//Create custom Exception class
String message; Defining a String type variable
Public myexception (String errormessagr) {//Parent class method
message = ERRORMESSAGR;
}
Public String GetMessage () {//overwrite GetMessage () method
return message;
}
}
public class Captor {//Create class
static int div (int x,int y) throws myexception{//definition method throws an exception
if (Y < 0) {//Determine if the parameter is less than 0
throw new MyException ("divisor cannot be negative");//exception information
}
Return x/y;//returned value
}
public static void Main (String args[]) {//Main method
try{//try statement containing statements that may have an exception
Div (3,-1);//Call method
}catch (myexception e) {//Handling custom exceptions
System.out.println (E.getmessage ()); Output exception information
}
catch (Exception e) {//Handle other exceptions
System.out.println ("Other exception occurred in the program");
Output hint information
}
}
}
This article is from the "Embedded Learning World" blog, please be sure to keep this source http://farsight.blog.51cto.com/1821374/1547925
Throws and throw keywords in Java