类1:public class LogicException extends RuntimeException {
//业务逻辑异常
/**
*
* @param message 异常信息
*/
public LogicException(String message) {
super(message);
}
/**
*
* @param message 异常信息
* @param cause 当前异常的根本原因
*/
public LogicException(String message, Throwable cause) {
super(message, cause);
}
}
类2:private static String[] arr={"张三","小张","小明","李四"};
public static void main(String[] args) {
try {
checkUsername("张三");
} catch (LogicException e) {
String errorMsg=e.getMessage();
System.out.println("给用户看"+errorMsg);
}
}
private static Boolean checkUsername(String username){
for (String name : arr) {
if(name.equals(username)){
throw new LogicException("很抱歉,"+username+"已经注册了!");
}
}
System.out.println("注册成功!");
return true;
}
}
[总结]
1.自定义异常:
class 异常类名 extends Exception
{
public 异常类名(String msg)
{
super(msg);
}
}
2.标识可能抛出的异常:
throws 异常类名1,异常类名2
3.捕获异常:
try{}
catch(异常类名 y){}
catch(异常类名 y){}
4.方法解释
getMessage() //输出异常的信息
printStackTrace() //输出导致异常更为详细的信息