软件编程
位置:首页>> 软件编程>> java编程>> Java中try catch处理异常示例

Java中try catch处理异常示例

作者:java时光  发布时间:2023-11-07 00:43:17 

标签:java,try,catch

 描述说明:

public class TryCatchStu {

 /*try catch:自己处理异常

  *try{

  * 可能出现异常的代码

  *}catch(异常类名A e){

  * 如果出现了异常类A类型的异常,那么执行该代码

  *}...(catch可以有多个)

  *finally{

  * 最终肯定必须要执行的代码(例如释放资源的代码)

  *}

  *代码执行的顺序:

  *1.try内的代码从出现异常的那一行开始,中断执行

  *2.执行对应的catch块内的代码

  *3.继续执行try catch 结构之后的代码

  *注意点:

  *1.如果catch内的异常类存在子父类的关系,那么子类应该在前,父类在后

  *2.如果finally中有return语句,那么最后返回的结果肯定以finally中的返回值为准

  *3.如果finally语句中有return,那么没有被处理的异常将会被吞掉

  *重写的注意点:

  *1.儿子不能比父亲的本事大

  *2.儿子要比父亲开放

  *3.儿子不能比父亲惹更大的麻烦(子类的异常的类型不能是父类的异常的父类型)

  *异常类Api:

  •   *1.getMessage():获取异常描述信息字符串

  •   *2.toString():返回异常类的包路径和类名和异常描述信息字符串

  •   *3.printStackTrace():除了打印toString的信息外,还要打印堆栈信息

  */

实例代码:


public static void main(String[] args)
{
 System.out.println(demo());
}
public static int demo(){
 GirlHome gh = new GirlHome("小陈陈",'男',28);
 try{
  gh.intoHome();
  System.out.println("进入了女生宿舍");
  return 0;
 }catch(SexOutException e){
  //System.out.println("出现了异常");
  //System.out.println(e);
  e.demo();
  e.printStackTrace();
 }catch (AgeOutException e) {
  // TODO: handle exception
 }finally{
  System.out.println("我必须被执行");
 }
 return 1;
 //System.out.println("愉快的一天结束啦");
}

class GirlHome {
public String name;
public char sex;
public int age;
public GirlHome(String name,char sex,int age)
{
 super();
 this.name = name;
 this.sex = sex;
 this.age = age;
}
//如果发现进入者是男的,那么抛出性别异常
public void intoHome() throws SexOutException,AgeOutException{
 if(sex!='女'){
  SexOutException se = new SexOutException(name+"你不是女的,滚!!!");
  throw se;
 }
 if(age>25){
  throw new AgeOutException(name+"你的年龄太大了,滚!!!!");
 }
 System.out.println(name+"开心的进入了宿舍");
}
public void demo()throws Exception{}
}

class SmallGirlHome extends GirlHome{
public SmallGirlHome(String name, char sex, int age)
{
 super(name, sex, age);
 // TODO Auto-generated constructor stub
}
@Override
public void intoHome() throws SexOutException,AgeOutException
{

}
public void demo()
{

}

class AgeOutException extends Exception{
public AgeOutException(String message){
 super(message);
}
}
class SexOutException extends Exception{
public SexOutException(String message){
 super(message);
}
public void demo(){
 System.out.println("爱啦啦阿拉");
}
}

来源:https://blog.csdn.net/wanghuiwei888/article/details/78818203

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com