First, the keyword explanation:
1.try catch: This includes code that is caught and processed if an exception occurs, and if there is an error between the code, it does not affect the execution of the program;
2.throw: The exception that is explicitly thrown in the program, such as the throw New Exception ();
3.throws: Indicates that the method may throw an exception, introduces an exception class through throw new Exception (), does not handle the exception within the method, and handles the exception by using the TYR catch statement;
4.finally: This code will be executed regardless of the exception program segment
Second, exception class commonly used methods:
Construction method: Public Exception ();
Public Exception (String s)://String S is a description of the exception;
Exception Handling methods:
Public String toString (): Returns the description of the current exception object information;
Public String getMessage (); Returns a detailed description of the current exception object information;
public void Printstacktrace (): Used to track the execution of stack contents when an exception event occurs;
Iii. Examples of custom exceptions:
Check for login information
Import java.util.*;
Class EXCEPTLGN extends runtimeexception{//Custom exception
EXCEPTLGN () {
Super ("Input username or password is wrong, please re-enter");
}
}
Class connectserver{
Private final String id= "test";
Private final String pwd= "123456";
void Connect (String id,string pwd) throws exceptlgn{//method declaration calling custom exception
if (this.id.equals (ID) &&this.pwd.equals (pwd)) {
SYSTEM.OUT.PRINTLN ("Emulation login server succeeded");
}else{
throw new Exceptlgn (); Throws an Object
}
}
}
public class Exceptionlogin {
public void Login (String id,string pwd) {
ConnectServer cs=new ConnectServer ();
try{
Cs.connect (ID,PWD);
}catch (RuntimeException e) {
System.out.println (E.getmessage ()); Throw exception when executing this method
System.out.println (E.tostring ());
}
}
public static void Main (string[] args) {
Exceptionlogin ext=new Exceptionlogin ();
Scanner sc=new Scanner (system.in);
System.out.println ("Please enter user name and password:");
String Id=sc.nextline ();
String Pwd=sc.nextline ();
Ext.login (ID, PWD);
}
Java Custom Exceptions