1.throws
throws抛出异常,通常是在类的声明阶段,
代表声明的异常抛出,但不进行处理;
当程序员不能处理出可能出现的异常时,就需要在方法声明阶段声明异常,那么在后续出现异常的情况下就能够知道异常的情况
避免了出现异常却不知道具体异常的情况
代码示例如下:
注意 在方法声明异常时需要在调用其的方法也声明异常
如代码中match2中声明了异常,main中也需要声明异常
public class testDemo {
private static String userName ="charge";
private static String passWord = "123456";
public static void main(String[] args)throws PasswordException,UserException {
Scanner scanner =new Scanner(System.in);
System.out.println("请输入您的用户名:");
String userN = scanner.nextLine();
System.out.println("请输入密码:");
String PA = scanner.nextLine();
match2(userN,PA);
}
public static void match2 (String un,String pa) throws
UserException,
PasswordException{
if (!testDemo.userName.equals(un)){
throw new UserException("用户名异常");
}
if(!testDemo.passWord.equals(pa)){
throw new PasswordException("密码错误");
}
System.out.println("登陆成功");
}
2.throw抛出异常
使用try并用throw抛出异常时,需要catch来捕获这个异常,
通常catch中编写处理异常的代码,
需要注意的是try中执行的语句在碰到异常时停止,去执行catch这个异常的语句,
之后继续执行try中的接下来的程序
代码如下:
public class testDemo {
private static String userName ="charge";
private static String passWord = "123456";
public static void main(String[] args)throws PasswordException,UserException {
Scanner scanner =new Scanner(System.in);
System.out.println("请输入您的用户名:");
String userN = scanner.nextLine();
System.out.println("请输入密码:");
String PA = scanner.nextLine();
match(userN,PA);
}
public static void match(String un,String pa){
if (!testDemo.userName.equals(un)){
try {
throw new UserException("用户名错误!");
}catch (UserException e){
e.printStackTrace();
}
}
if (!testDemo.passWord.equals(pa)){
try {
throw new PasswordException("密码错误!");
}catch (PasswordException e){
e.printStackTrace();
}
}
System.out.println("登陆成功");
}
可以看到一个throws抛出的异常首先是说main中出现了异常,程序并没有执行到最后,说明程序将异常抛给了上一层,
throw则只出现了定义的异常,且程序执行到了最后,这是由于我在catch中并没有对异常进行处理,printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因,然后继续向下执行