星空网 > 软件开发 > Java

JAVA 处理程序异常,(try、catch、finally),(thorws)

一、try语句:

    try{//这里写可能出现异常的程序}

    catch(Exception e){//这里写如果出现异常怎么处理的程序}

 

二、throws语句

  语法:函数方法()  throws Exception {}

三、try语句示例:

import java.util.Scanner;public class Index{  public static void main(String[] args){    Scanner in  =  new Scanner(System.in);    try{      System.out.println("请输入一个数字:");      int a  =  in.nextInt();      System.out.println("请输入一个数字:");      int b  =  in.nextInt();      int c  =  a%b;      System.out.println("余数为:"+c);    }    catch(Exception e){      System.out.println("输入错误");    }    //Exception 异常的意思    //后面的e 可以随便写,一遍写e,因为这个是一个对象    System.out.println("程序继续执行");  }}

 

四、throws语句示例:

//throws Exception 的用法import java.util.Scanner;public class Index{  public static void main(String[] args) throws Exception  //程序中的异常处理代码都不能处理所以反馈到这里  {    try{      Myclass.t();  //调用静态方法,测试异常,如果还有错,在向上反馈,在往上反馈就是try语句,如果这个语句在无法处理,就反馈到主函数    }    catch(Exception e){      System.out.println("输入错误");    }    System.out.println("程序继续执行");  }}class Myclass{  static void t() throws Exception  //如果本方法有错,向上反馈  {    Scanner in  =  new Scanner(System.in);    System.out.println("请输入一个数字:");    int a  =  in.nextInt();    System.out.println("请输入一个数字:");    int b  =  in.nextInt();    int c  =  a%b;    System.out.println("余数为:"+c);  }}

 

五、finally

//finally 的用法import java.util.Scanner;public class Index{  public static void main(String[] args) throws Exception    {    try{      Myclass.t();    }    catch(Exception e){      System.out.println("输入错误");    }    finally{      System.out.println("不管是否异常,我都会继续执行");//finally就是代表这个意思,这个是跟try一起使用的    }  }}class Myclass{  static void t() throws Exception    {    Scanner in  =  new Scanner(System.in);    System.out.println("请输入一个数字:");    int a  =  in.nextInt();    System.out.println("请输入一个数字:");    int b  =  in.nextInt();    int c  =  a%b;    System.out.println("余数为:"+c);  }}

 




原标题:JAVA 处理程序异常,(try、catch、finally),(thorws)

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

通途ERP:https://www.ikjzd.com/w/1541
越域网_分销平台:https://www.ikjzd.com/w/1542
PaaSoo云通讯_国际短信平台:https://www.ikjzd.com/w/1543
广州洋盒子:https://www.ikjzd.com/w/1544
希塔电商:https://www.ikjzd.com/w/1545
胡萝卜村:https://www.ikjzd.com/w/1546
上海滑雪场门票价格?:https://www.vstour.cn/a/408235.html
德国有那些品牌公司:https://www.vstour.cn/a/408236.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流