Java学习笔记08

Java 笔记08

Java中所有对象的根类
===>java.lang.object

异常

  1. 异常中所包含的类:Throwable (祖先),被继承于:
    • Error 错误==>运行时系统内部出错,不能忍受==>堆栈溢出<==程序写的结构就有问题
    • Execption 异常:
  2. Throw 抛出异常的语句==>用在函数上,后面跟异常类名
  3. Throws 声明抛出异常时使用的关键字==>用在函数内,后面跟异常对象。

自定义异常

  1. 自定义类继承Exception或者其子类;
  2. 通过构造函数定义异常信息;
  3. 通过Throw将异常抛出;

捕捉异常或错误语句的基本结构

try{
    需要监测的代码;
}catch(异常类 变量){
    异常处理代码;
}finally{---->这个模块可以不写,如果写了就一定会执行
    一定会执行的代码;
}
注:finally只有一种情况不会执行,那就是在前面执行了System.exit(0);

实例代码

package Java1;

public class java_01 {

    public static void main(String[] args) {
        int[] arr = null;
        //int[] arr =new int[4];
        System.out.println(getLength(arr));
    }

    public static int getLength(int[] arr) {
        int len = 0;
        try {
            len=arr.length;
        } catch (Exception e) {
            System.out.println("出错了"+e.getMessage());
        } finally {
            System.out.println("程序执行完了...");
        }
        return len;
    }
}
输出:
出错了null
程序执行完了...
0

异常或错误的层级关系

验证catch中捕捉错误或者异常(例如栈溢出)时可以用包含该异常或错误的关系树上的类代替

实例代码

package Java1;

public class java_01 {

    public static void main(String[] args) {
        try {
            sayhello();
        } catch (VirtualMachineError e) {
            System.out.println("出错啦..."+e.getMessage());
        }
    }

    public static void sayhello() {
        System.out.println("sayhello");
        sayhello();
    }
}

同时抓取多个异常的语法

基本语法

try{
    ...
}
catch(MyException1 e){
    ...
}
catch(MyException2 e){

}

**注:按照异常的捕捉范围必须是从上到下按照范围从小到大排列即
MyException1

验证实例-catch()内异常顺序调整会报错

package Java1;

class Person{
    private int age;
    public int getAge() {
        return age;
    }
    //使用异常
    public void setAge(int age) throws AgeTooBigException {
        if (age > 150) {
            throw new AgeTooBigException();//年龄太大异常
        }
        this.age=age;
    }
}
//年龄太大异常
class AgeTooBigException extends Exception{
    private String info;
    //构造函数默认调用父类的空构造,但是没有,因此要用super()
    public AgeTooBigException(String info) {
        this.info=info;
    }
    public AgeTooBigException() {
        this("年龄太大!");
    }
    public void printError() {
        System.out.println(info);
    }
}

public class java_01 {

    public static void main(String[] args) {
        Person person = new Person();
        try {
            person.setAge(160);
        } catch (AgeTooBigException e) {//范围最小
            e.printError();
        } catch (Exception e) {//catch的范围次小
            e.printStackTrace();
        } catch (Throwable e) {//最大
            e.printStackTrace();
        }
    }

}
输出:年龄太大!

练习

思路

package Java1;

class Person{
    private int age;
    public int getAge() {
        return age;
    }
    //使用异常
    public void setAge(int age) throws AgeTooBigException, 
                                       AgeInvalidException,
                                       AgeTooSmallException{
        if (age > 150) {
            throw new AgeTooBigException();//年龄太大异常
        }else if (age==0) {
            throw new AgeTooSmallException();//年龄太小异常
        }else if (age<0) {
            throw new AgeInvalidException("年龄非法");
        }
        this.age=age;
    }
}
//年龄方法异常
class AgeInvalidException extends Exception{
    private String info;
    public AgeInvalidException(String info) {
        this.info=info;
    }
    public void printError() {
        System.out.println(info);
    }
}
//年龄太大异常
class AgeTooBigException extends AgeInvalidException{
    //构造函数默认调用父类的空构造,但是没有,因此要用super()
        public AgeTooBigException(String info) {
            super(info);
        }
        public AgeTooBigException() {
            this("年龄太大");
        }
}
//年龄太小异常
class AgeTooSmallException extends AgeInvalidException{
    //构造函数默认调用父类的空构造,但是没有,因此要用super()
    public AgeTooSmallException(String info) {
        super(info);
    }
    public AgeTooSmallException() {
        this("年龄太小");
    }
}
public class java_01 {

    public static void main(String[] args) {
        Person person = new Person();
        try {
            person.setAge(-100);
        } catch (AgeTooBigException e) {//并列,无所谓
            e.printError();
        } catch (AgeTooSmallException e) {//并列无所谓
            e.printError();
        }catch (AgeInvalidException e) {//catch的范围最大,方最下面
            e.printError();
        } 
    }

}

运行时异常和非运行时异常

  1. 运行时异常—>不需要在声明抛出语句,也没有try catch

    1. 其中最典型的异常就是空指针异常
      实例:
      package Java1;

      class Person{
          private int age;
          public int getAge() {
              return age;
          }
          //使用异常
          public void setAge(int age) {
              if (age > 150) {
                  throw new AgeTooBigException();//年龄太大异常
              }else if (age==0) {
                  throw new AgeTooSmallException();//年龄太小异常
              }else if (age<0) {
                  throw new AgeInvalidException("年龄非法");
              }
              this.age=age;
          }
      }
      //年龄方法异常
      class AgeInvalidException extends RuntimeException{
          private String info;
          public AgeInvalidException(String info) {
              this.info=info;
          }
          public void printError() {
              System.out.println(info);
          }
      }
      //年龄太大异常
      class AgeTooBigException extends AgeInvalidException{
          //构造函数默认调用父类的空构造,但是没有,因此要用super()
              public AgeTooBigException(String info) {
                  super(info);
              }
              public AgeTooBigException() {
                  this("年龄太大");
              }
      }
      //年龄太小异常
      class AgeTooSmallException extends AgeInvalidException{
          //构造函数默认调用父类的空构造,但是没有,因此要用super()
          public AgeTooSmallException(String info) {
              super(info);
          }
          public AgeTooSmallException() {
              this("年龄太小");
          }
      }
      public class java_01 {
      
          public static void main(String[] args) {
              Person person = new Person();
              person.setAge(-100);
      
          }
      
      }
      编译时没问题,当时运行时会出问题
      
  2. 非运行时异常—>需要声明抛出语句,而且要try catch<—上面代码除了上一个实例其余全部都是。
  3. 构造函数中也可以使用异常语句来抛出异常–如果非要抛出也是允许的
    1.实例
    package Java1;

    class Person{
        private int age;
        public int getAge() {
            return age;
        }
        public Person(int age) throws AgeInvalidException {//在运行时异常时,如果非要抛也是允许的
            if (age>200 || age<0) {
                throw new AgeInvalidException("非法值");
            }
            this.age=age;
        }
        //使用异常
        public void setAge(int age) {
            if (age > 150) {
                throw new AgeTooBigException();//年龄太大异常
            }else if (age==0) {
                throw new AgeTooSmallException();//年龄太小异常
            }else if (age<0) {
                throw new AgeInvalidException("年龄非法");
            }
            this.age=age;
        }
    }
    //年龄方法异常
    class AgeInvalidException extends RuntimeException{
        private String info;
        public AgeInvalidException(String info) {
            this.info=info;
        }
        public void printError() {
            System.out.println(info);
        }
    }
    //年龄太大异常
    class AgeTooBigException extends AgeInvalidException{
        //构造函数默认调用父类的空构造,但是没有,因此要用super()
            public AgeTooBigException(String info) {
                super(info);
            }
            public AgeTooBigException() {
                this("年龄太大");
            }
    }
    //年龄太小异常
    class AgeTooSmallException extends AgeInvalidException{
        //构造函数默认调用父类的空构造,但是没有,因此要用super()
        public AgeTooSmallException(String info) {
            super(info);
        }
        public AgeTooSmallException() {
            this("年龄太小");
        }
    }
    public class java_01 {
    
        public static void main(String[] args) {
            Person person = new Person(3000);
            person.setAge(-100);
    
        }
    
    }
    输出:
    Exception in thread "main" Java1.AgeInvalidException
        at Java1.Person.<init>(java_01.java:10)
        at Java1.java_01.main(java_01.java:59)
    

异常的一些细节

  1. Runtime异常以及其子类如果在函数中被throw抛出,可以不用再函数上声明;
  2. 一个方法被覆盖时,覆盖它的方法必须抛出相同的异常或者是异常的子类;
  3. 如果父类抛出多个异常,那么重写(覆盖)方法必须抛出那些异常的一个子集,不能抛出一个新的异常。

总结起来一句话:方法覆盖时,只能抛出相同异常或者子类,范围可以缩小,不能放大。

实例代码

package Java1;

class People{
    public int age; 
    public void setAge(int age) throws AgeInvalidException {
        //此处的异常范围应该是一个父类异常
        if (age>200 || age<0) {
            throw new AgeInvalidException();
            //这里也可以是父类的子类异常AgeTooSmallException或者AgeTooBigException,因为非法异常已经包含了这两个子类异常了。
        }
        this.age=age;
    }
}
class Chinese extends People{
    public void setAge(int age) throws AgeTooBigException,AgeTooSmallException{
        //此处的异常应该是一个子类异常
        if (age<0) {
            throw new AgeTooSmallException();
        }
        if (age>200) {
            throw new AgeTooBigException();
        }
    }
}
//年龄方法异常
class AgeInvalidException extends Exception{
}
//年龄太大异常
class AgeTooBigException extends AgeInvalidException{

}
//年龄太小异常
class AgeTooSmallException extends AgeInvalidException{

}

public class Exx {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

大练习

第一题代码

package Java_home_03;

import java.util.Scanner;

class Triangle{
    double a = 0.0;
    double b = 0.0;
    double c = 0.0;
    public Triangle(double a, double b, double c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
    public void judeLegal() throws TriangleExistException,
                                   TriangleJudeLegalException{
        if (a <= 0 || b <= 0 || c <= 0) {
            throw new TriangleJudeLegalException("三条边中存在负值,三角形不成立!");
        }
        if (a+b <= c || a+c <= b || b+c <= a) {
            throw new TriangleExistException();
        }
    }
}
class TriangleJudeLegalException extends Exception{
    private String info;
    public TriangleJudeLegalException(String info) {
        this.info = info;
    }
    public void OutputInfo() {
        System.out.println(info);
    }
}
class TriangleExistException extends TriangleJudeLegalException{
    public TriangleExistException(String info) {
        super(info);
    }
    public TriangleExistException() {
        this("三条边不满足三边不等式,三角形不能存在!");
    }
}
public class java08_home1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入a的值:");
        double a = scanner.nextDouble();
        System.out.println("请输入b的值:");
        double b = scanner.nextDouble();
        System.out.println("请输入c的值:");
        double c = scanner.nextDouble();
        Triangle triangle = new Triangle(a, b, c);
        try {
            triangle.judeLegal();
            System.out.println("三角形的三条边为:"+a+" "+b+" "+c);
        }catch (TriangleExistException e) {
            e.OutputInfo();
        } catch (TriangleJudeLegalException e) {
            e.OutputInfo();
        }
    }

}
结果:
请输入a的值:
-1
请输入b的值:
2
请输入c的值:
5
三条边中存在负值,三角形不成立!

第二题代码

package Java_home_03;

import java.util.Scanner;

class Person{
    public int year;
    public int month;
    public int day;
    public Person(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void setBirthDay() throws BirthdayInvaluedException,
                                     BirthdayYearInvaluedException,
                                     BirthdayMonthInvaluedException,
                                     BirthdayDayInvaluedException{
        if (year < 1970 || year > 2018) {
            throw new BirthdayYearInvaluedException();
        }
        if (month < 1 || month > 12)
        {
            throw new BirthdayMonthInvaluedException();
        }
        //这里二月因为瑞年的情况有所区别,且除了2月之外,不同的月也有30天和31天的差别
        //第一步先判断是不是瑞年--重新定义一个判断瑞年方法
        switch (month) {
        case 2:
            if (JudgeRuinian(year)) {
                if (day <1 || day > 29) {//如果是瑞年而2月的输入大于29或者小于1的话抛异常
                    throw new BirthdayInvaluedException("瑞年,2月份输入的日期无效");
                }
            }
            else {
                if( day <1 || day > 28) {//如果不是闰年而2月的输入是大于28天或者小于1的话抛异常
                    throw new BirthdayInvaluedException("非瑞年,2月份输入的日期无效");
                }
            }
            break;
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            if (day < 1 || day > 31) {//如果1,3,5,7,8,10,12月份输入的大于31小于1的话抛异常;
                throw new BirthdayDayInvaluedException();
            }
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            if (day < 1 || day > 30) {//如果4,6,9,11月份输入的大于30小于1的话抛异常;
                throw new BirthdayDayInvaluedException();
            }
            break;
        default:
            break;
        }
        System.out.println("year: "+year+" month: "+month+" day: "+day);
    }
    private boolean JudgeRuinian(int year) {
        if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
            //System.out.println("是闰年");
            return true;
        }else{
            //System.out.println("不是闰年");
            return false;
        }
    }
}
class BirthdayInvaluedException extends Exception{
    private String info;
    public BirthdayInvaluedException(String info) {
        this.info = info;
    }
    public void OutputInfo() {
        System.out.println(info);
    }
}
class BirthdayYearInvaluedException extends BirthdayInvaluedException{
    public BirthdayYearInvaluedException(String info) {
        super(info);
    }
    public BirthdayYearInvaluedException() {
        this("输入的年龄无效");
    }
}
class BirthdayMonthInvaluedException extends BirthdayInvaluedException{
    public BirthdayMonthInvaluedException(String info) {
        super(info);
    }
    public BirthdayMonthInvaluedException() {
        this("输入的月份无效");
    }
}
class BirthdayDayInvaluedException extends BirthdayInvaluedException{
    public BirthdayDayInvaluedException(String info) {
        super(info);
    }
    public BirthdayDayInvaluedException() {
        this("输入的该月日期无效");
    }
}
public class Java08_home2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入年份:");
        int year = scanner.nextInt();
        System.out.println("请输入月份:");
        int month = scanner.nextInt();
        System.out.println("请输入该月日期:");
        int day = scanner.nextInt();
        Person person = new Person(year, month, day);
        try {
            person.setBirthDay();
        } catch (BirthdayYearInvaluedException e) {
            e.OutputInfo();
        } catch (BirthdayMonthInvaluedException e) {
            e.OutputInfo();
        } catch (BirthdayDayInvaluedException e) {
            e.OutputInfo();
        } catch (BirthdayInvaluedException e) {
            e.OutputInfo();
        }
    }

}
结果:
请输入年份:
2001
请输入月份:
2
请输入该月日期:
29
非瑞年,2月份输入的日期无效

Package–包==>类似文件夹

  1. 首先,以后可能用到的文件扩展名为:
    1. jar - java archive 归档
    2. ear - enterprise archive
    3. war - web archive
    4. har - hadoop archive
    5. tar - Linux archive <—Linux下的归档
  2. 包的作用:
    1. 对类进行分类管理;
    2. 给类提供多层命名空间;
    3. 写在程序文件的第一行;
    4. 类名的全称是包名.类名;
    5. 包也是一种封装形式;
  3. 包之间的访问
    1. 被访问的包中类的权限必须是public
    2. 类中的成员权限public或者protected
    3. protected是为其它包中的子类提供的一种权限
  4. 命名规则:全小写

运行时出现的问题—Cmd运行java

代码如下所示:

这样系统会报错的

没有完整的引用的包名及其路径,正确的姿势是这样的:

下面是根据包名自动创建目录并把class文件放进去

最后根据路径再运行一下的效果如下:

需要记住的命令

  1. mkdir classes//创建目录
  2. javac -d classes PackageDemo1.java//编译java文件并存放到指定目录classes里面的一个目录<—-在classes里面根据包名自动创建。
  3. java -cp classes com.it18zhang.java.PackageDemo1//运行程序,类全限定名。
  4. -cp 参数后面是类路径,是指定给解释器到哪里找到你的.class文件,可以使相对路径也可以绝对路径,详情请见CSDN博客https://blog.csdn.net/shixiaoguo90/article/details/50607716
    相对路径

    绝对路径

修饰符的访问权限

范围publicprotecteddefaultprivate
同类OKOKOKOK
同包OKOKOKNO
子类OKOKNONO
不同包OKNONONO

1. private //私有的不能继承;
2. public //都可以
3. protected //受保护,针对其它包中的子类
4. default //默认,不写,不同包不能继承
1. 一个java源文件包中只能有一个public类
2. 如果类使用public修饰,文件名必须是类名

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值