栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

java异常

Java 更新时间:发布时间: 百科书网 趣学号

java异常
* 异常是【程序运行时】出现的不正常现象。
异常处理机制?
为什么要有异常处理机制?
*用if…else来不漏洞不是长久之计:
*1)代码臃肿;
*2)处理异常的代码和执行功能代码在一起;
*3)不能堵住所有的漏洞;
异常处理机制:
*(1)try…catch:
异常处理机制的执行原理:
*(1)try语句块:有可能出现异常的代码;
*(2)catch语句块:如果异常被成功捕获了,处理异常的代码;
*(3)如果出现异常,try语句块里出现异常的语句开始,try语句块之后的代码就都不执行了。
*(4)如果catch了异常,执行异常处理的语句。执行完之后程序不会中断,还会继续执行。
*(5)如果没catch住,程序一样会中断。
*
*catch语句块:
*1)printStackTrace();
*2)getMessage();

  • System.out.println(e.getMessage());
    *3)System.err.println(自定义的信息);
    *4)System.out.println(自定义的信息);
    *5)toString();
  • System.out.println(e);
    */
    import java.util.Scanner;

public class Test {

   public static void main(String[] args) {
           
           Scanner input=new Scanner(System.in);
           int n1,n2,n;
           
           try{
                   System.out.println("请输入被除数");
                   n1=input.nextInt();//---new InputMismatchException();
                   System.out.println("请输入除数");
                   n2=input.nextInt();
                   n=n1/n2;
                   System.out.println(n);
                   
           }catch(Exception e){
                   
                   //e.printStackTrace();
                   
                   //System.out.println(e.getMessage());
                   
                   //System.err.println("数据格式不对。");
                   
                   System.out.println(e);
           }
           
           System.out.println("Hello World.");

   }

}
异常处理机制:try后跟多个catch语句块;
try…catch…catch:
执行原理:
从上到下依次匹配catch语句块中的异常类型,执行第一个匹配到的catch语句块;
如果后面还有匹配的,也不执行了,跳出try…catch结构,执行后续语句。
如果能catch异常,就执行一条。

catch语句的顺序:子类型放前面,父类型放后面。
*/
import java.util.Scanner;

public class Test2 {

   public static void main(String[] args) {
           
           Scanner input=new Scanner(System.in);
           int n1,n2,n;
           
           try{
                   System.out.println("请输入被除数");
                   n1=input.nextInt();//---new InputMismatchException();
                   System.out.println("请输入除数");
                   n2=input.nextInt();
                   n=n1/n2;
                   System.out.println(n);
                   
           }catch(InputMismatchException e){
                   
                   System.out.println("输入数据的格式不匹配。");
                   
           }catch(ArithmeticException e){
                   
                   System.out.println("除数不能是零。");
                   
           }catch(Exception e){
                   System.out.println("程序出现错误。");
           }
           
           System.out.println("Hello World.");

   }

}

		异常处理机制:try...catch...finally;

			try{


}catch(){

}finally{

}

finally的执行结果:1)没有异常:能执行。
2)有异常,捕获到了:能执行。
3)有异常,没捕获到:能执行。
4)finally语句前如果有return,先执行finally,再执行return。
5)System.exit(1);退出虚拟机,只有这种情况,finally不执行。

finally:一般是收尾的语句,如关闭资源,断开连接等。

*/
import java.util.Scanner;

public class Test3 {

   public static void main(String[] args) {
           
           Scanner input=new Scanner(System.in);
           int n1,n2,n;
           
           try{
                   System.out.println("请输入被除数");
                   n1=input.nextInt();//---new InputMismatchException();
                   System.out.println("请输入除数");
                   n2=input.nextInt();
                   n=n1/n2;
                   System.out.println(n);
                   
           }catch(InputMismatchException e){
                   
                   System.out.println("输入数据的格式不匹配。");
                   //return;
                   System.exit(1);
                   
           }finally{
                   
                   System.out.println("谢谢使用!");
           }
           

   }

}

		异常抛出的两种形式:
  1. 系统隐式抛出;int n=10/0;—隐式抛出一个异常;

  2. 手动抛出异常:throw new Exception();
    public class Person {

    // 属性;
    private String name;
    private int age;
    private String sex;
    
    // getter和setter;
    public String getName() {
            return name;
    }
    
    public void setName(String name) {
            this.name = name;
    }
    
    public int getAge() {
            return age;
    }
    
    public void setAge(int age) {
            this.age = age;
    }
    
    public String getSex() {
            return sex;
    }
    // 第一种方法;
    
    
    // 第二种方法;手动抛出异常;
    
    
    
    public void setSex(String sex) {
    
    if (!"男".equals(sex) && !"女".equals(sex)) {
    
            try {
                    throw new Exception();//这种类型可能是检查异常,在程序运行前必须处理。
            } catch (Exception e) {
                    
                    System.out.println("性别输入不合理。");
            }
    
    } else {
    
            this.sex = sex;
    }
    

}

   @Override
   public String toString() {
           return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
   }

}

		1.try...catch;

2.throws

			*throws:方法声明异常;如果多个异常类型,用逗号分隔;

*public void setAge(int age) throws InputMismatchException,ArithmeticException {
*…
*}

调用此方法的方法负责处理异常。

public class Person {

   // 属性;
   private String name;
   private int age;
   private String sex;

   // getter和setter;
   public String getName() {
           return name;
   }

   public void setName(String name) {
           this.name = name;
   }

   public int getAge() {
           return age;
   }


   public void setAge(int age) throws Exception {//声明异常
           
           if(age<0||age>150){
           
                           throw new Exception();
                   
           }else{
                   this.age=age;
           }
   }

   public String getSex() {
           return sex;
   }


   public void setSex(String sex) {

   if (!"男".equals(sex) && !"女".equals(sex)) {
   
           try {
                   throw new Exception();
           } catch (Exception e) {
                   
                   System.out.println("性别输入不合理。");
           }

   } else {

           this.sex = sex;
   }

}

}

// 测试类

public class Test {

   public static void add() throws Exception{
           
   }

   public static void main(String[] args)   {
           
           Person p=new Person();
           p.setName("小明");
           
   
           try {
                   p.setAge(180);//此方法声明了异常,主方法负责处理;
           } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
           }
   
           
           
           p.setSex("保密");
           
           System.out.println(p);
   }

}
*两种异常:
*(1)RuntimeException:程序不要求必须处理;
(2)checked异常(检查异常): 程序运行之前必须做好处理措施,否则编译报错:Unhandled Exception type Exception.
1.程序不会中断了,处理异常后,能继续执行。
2.可以向用户提供友好的异常信息。
3.将程序的正常流程与错误处理分开,有利于代码的编写和维护。
/

*方法的重写:子类声明的异常类型必须和父类一致,或是父类异常类型的子类。
*
*/
public class Person {

   public void show() throws IOException{
           
   }

}

class Student extends Person{

   @Override
   public void show() throws FileNotFoundException{
           //FileNotFoundException是IOException的子类;如果用Exception就报错;
   }

}

		/*

*自定义异常:1.继承系统的异常类;
*public class SexException extends Exception {

   }
   
   2.添加构造方法;
           public SexException() {
           
   }

   public SexException(String message) {
           super(message);
           
   }
  •   		public class SexException extends Exception {
    
     public SexException() {
             
     }
    
     public SexException(String message) {
             super(message);
             
     }
    

}

public class Person {

   // 属性;
   private String name;
   private int age;
   private String sex;

   // getter和setter;
   public String getName() {
           return name;
   }

   public void setName(String name) {
           this.name = name;
   }

   public int getAge() {
           return age;
   }
   
   public void setAge(int age) {                
           
         this.age=age;
   }

   public String getSex() {
           return sex;
   }

   
   public void setSex(String sex) {

   if (!"男".equals(sex) && !"女".equals(sex)) {
   
            try {
                           throw new SexException("性别输入不合理。");
                   } catch (SexException e) {
                           System.out.println(e.getMessage());
                   }
                   

   } else {

           this.sex = sex;
   }

}

}
*throw和throws:
*throw和throws:
*1)所在位置不一样:throw出现在方法体里;

  •         throws出现在方法声明处;
    

*2)后面跟的内容不一样:throw new Exception();异常对象;跟一个对象;

  •           throws Exception;异常类型;跟多个异常类型,用逗号分隔;
    

*3)功能不一样:throw:抛出异常;

  •      throws:当作异常处理方式,向上抛出异常。
    
      	1.运行时异常:
    

java.lang.ArrayIndexOutOfBoundsException;
java.lang.NullPointerException;
java.util.InputMismatchException;
java.lang.ArithmeticException;
java.lang.ClassCastException;

2.检查异常:
ClassNotFoundException
IOException
*2.异常的危害?

  • 1)从出现异常的语句开始,程序就中断了。
  • 2)提供异常的信息不友好。
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1032997.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号