Hello ,大家好,国庆第一天,为你们带来Java的异常类讲解🎓,希望本文对您有所帮助
所谓异常就是程序运行时可能出现的一些错误,例如数组下标越界、出现空指针异常或者是算数异常
int number = Integer.parseInt("ab89");
可能大家在程序报出异常的时候也没有去自己看过是什么异常,这里我就给出运行时的报错截图给大家看看
假如我们遇到了无法处理的情况,Java方法可以抛出一个异常,但是这个异常要手动去抛出,而不是编译器帮你抛出,所以对于上述一些常见的异常,我们应该在实践的过程中将它牢记于心❤️
所谓声明检查时异常,就是要通过throws关键字,在方法体的首部,抛出在这个方法体中可能会出现的异常
public FileInputStream(String name)throws FileNotFoundException
public image LoadImage(String s)throws DileNotFoundException,EOFExcetion
void drawImage(int i)throws ArrayIndexOutofBoundsException
知道了如何去声明一个检查型异常,接下我们要学会如何去抛出一个异常
throw关键字
,而不是上面我们说到的throws
,这一点大家一定要区分,很重要,具体如何去操作,我们先来看一下吧public class test4 {
public static int divide(int x, int y) throws ArithmeticException{
//抛出可能会发生的异常
if(y == 0) {
throw new ArithmeticException("y == 0");
//具体执行会抛出异常的动作
}
return x / y;
}
public static void main(String[] args) {
try{
int ret = divide(10,5);
System.out.println(ret);
}catch (ArithmeticException e){
e.printStackTrace();
System.out.println("异常警告,除数为0");
}finally {
System.out.println("程序结束");
}
}
}
throw new ArithmeticException
初步了解了如何抛出异常后我们来看一下抛出异常的时机
public class test5 {
static class Person implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person(); //*不推荐*
Person person2 = (Person) person1.clone();
}
}
CloneNotCupportedException
这个异常类,从开头的思维导图可以知晓,其为编译时异常,也就是受查异常,这不属于我们上面所说的运行时异常,尽量不要去声明,这个异常的话是在编译阶段就会给你报错,所以我们要手动地去声明这个异常或自己抛出异常,所以通过throws关键字在方法体首部抛出了这个异常public static void main(String[] args){
//受查异常
Person person1 = new Person();
try {
Person person2 = (Person) person1.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
面对老板的质疑,看来我们不得不学习这个语句块了,才能对异常的处理灵活可靠⛸
public class test2 {
public static int fun(){
int[] arr = {2,3,1};
arr = null;
try{
System.out.println(arr[3]);
return 1; //不会被执行
}catch(NullPointerException e1){
e1.printStackTrace();
System.out.println("捕获到了空指针异常");
return 3;
}
return 0;
}
public static void main(String[] args) {
int ret = fun();
System.out.println("ret = " + ret);
}
}
当前,有些时候我们可能需要捕获的不止一个异常,就像一个数组可能会出现数组越界,也可以会出现空指针异常,这我们在实际开发的过程中都要能关注到
public static int fun(){
int[] arr = {2,3,1};
//arr = null;
try{
System.out.println(arr[3]);
return 1; //不会被执行
}catch(NullPointerException e1){
e1.printStackTrace();
System.out.println("捕获到了空指针异常");
return 3;
}catch(ArrayIndexOutOfBoundsException e2){
e2.printStackTrace();
System.out.println("捕获到了数组越界异常");
}finally {
//finally中的代码一定会被执行
System.out.println("程序运行结束");
//return 2;
// 不建议在finally中出现return语句,因为一定会return此处的数据
}
return 0;
}
catch(NullPointerException e1 | ArrayIndexOutOfBoundsException e2)
让我们来看一个具体的小例子
public class test3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
int n = sc.nextInt();
System.out.println(n / 10);
} catch (ArithmeticException e) {
e.printStackTrace();
}finally {
sc.close();//关闭输入器
}
}
}
当然,如果有了finally子句,也是可以不写catch子句,比如就像下面这样
InPutStream in = ...;
try{
code for might throw exceptions
} finally{
in.close();
}
我们再来看一种,就是内外嵌套的try语句
InPutStream in = ...;
try{
try{
code for might throw exceptions
} finally{
in.close();
}
}
catch(IOException e){
show error messsage
}
初步了解了try&catch语句块,接下来让我们去看一下使用这和语句块需要注意点什么
1、 catch块当中,一定要捕获相应的异常,如果程序抛出的异常在catch块当中,不能被捕获。那么就会交给JVM处理。
2、可以通过catch来捕获多个异常。
3、不建议大家直接捕获Exception。
4、finally块当中的代码,终究会被执行的。
5、不建议在finally当中出现return语句。
了解了如何抛出异常,清楚了try&catch子句以及finally的执行原理,接下来我们自己来动手写一个异常类吧
/**
* 自定义异常类
*/
//一定要继承一个异常父类
class MyException extends RuntimeException{
public MyException() {
}
public MyException(String message) {
super(message);
}
}
public class test6 {
public static void func(int x){
if(x == 10){
throw new MyException("x == 10");
}
}
public static void main(String[] args) {
try{
func(10);
}catch (MyException e){
e.printStackTrace();
System.out.println("发生异常");
}finally {
System.out.println("程序正常结束");
}
}
}
好,学完所有关于异常类的知识后,我们来做一个项目感受一下异常类在显示现实生活中是如何运用的
/**
* 登录检测 - 普通版
*/
public class test7 {
private static String UserName = "abcde";
private static String PassWord = "12345";
public static void login(String name, String code){
if(!UserName.equals(name)){
System.out.println("账户错误");
}else if(!PassWord.equals(code)){
System.out.println("密码错误");
}else{
System.out.println("登录成功");
}
}
public static void main(String[] args) {
login("abcde","12345");
}
}
接着我们用异常类的知识去实现一下
/**
* 登录检测 - 精良版
*/
class UserException extends Exception{
//自定义异常类最好使用Exception
public UserException() {
}
public UserException(String message) {
super(message);
}
}
class PassWordException extends Exception{
public PassWordException() {
}
public PassWordException(String message) {
super(message);
}
}
public class test8 {
private static String UserName = "abcde";
private static String PassWord = "12345";
public static void login(String name, String password) throws
UserException,PassWordException{
if(!UserName.equals(name)){
throw new UserException("用户名错误");
}else if(!PassWord.equals(password)){
throw new PassWordException("密码错误");
}else{
System.out.println("登录成功");
}
}
public static void main(String[] args) {
try{
login("abcde","12345");
}catch (UserException userException){
userException.printStackTrace();
}catch (PassWordException passWordException){
passWordException.printStackTrace();
}
}
}
最后,感谢您对本文的观看,如果疑问请于评论区留言或私信我🌸