java异常及其常用类

目录

 

1.异常

 Java异常的概念

 Java异常的分类

 异常的捕获和处理

 运行期出现的错误

 自定义异常

2.常用类

 字符串相关类(String 、StringBuffer、StringBuilder)

String类常用方法

测试String 和StringBuffer是否操作的是原对象

 算法及数组工具类(Arrays)

 日期类

SimpleDateFormat

 基本数据类型包装类

 Math类


  • 1.异常

  •  Java异常的概念

异常(Exception)即例外,程序没有按自己预想的结果运行出来,出现了非正常情况,即“程序得病了”。怎么让我们写的程序做出合理的处理,不至于崩溃是我们关注的核心。 异常机制就是当程序出现错误,程序如何安全退出的机制。

  •  Java异常的分类

 *     Throwable:
 *         1.Error:不受程序员控制
 *             1)Unchecked Exception
 *         2.Exception
 *             1)Checked Exception       检查时异常|编译时异常:如果出现了编译时异常,必须对程序作出一些处理,否则无法运行
 *             2)Runtime Exception       运行时异常:凡是运行时异常都会直接或者间接地继承Runtime Exception,需要增加程序的                                                          健壮性去解决

 * 几种常见的异常:
 *      1.java.lang.NullPointerException  空指针异常
 *         2.java.lang.ArithmeticException   数学异常
 *         3.java.lang.ArrayIndexOutOfBoundsException 索引越界异常
 *         4.NegativeArraySizeException 负数异常
 *         5.java.lang.ClassCastException 类型准换异常
 *         6.java.lang.NumberFormatException 数字格式异常
 *         以上都属于运行时异常

package day12;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class ExceptionDemo2 {
	public static void main(String[] args) throws FileNotFoundException {
		// java.lang.NullPointerException ---空指针异常
		// String s = null;
		// System.out.println(s.charAt(0));

		// java.lang.ArithmeticException: / by zero ---数学异常>>除零异常
		// System.out.println(5/0);

		// java.lang.ArrayIndexOutOfBoundsException ---索引越界异常
		// int[]arr = new int[5];
		// System.out.println(arr[5]);

		// java.lang.NegativeArraySizeException ---负数异常
		// int[]arr1 = new int[-5];

		// java.lang.ClassCastException ---类型转换异常
		// Son son = (Son)new Error();
		// son.test();

		// java.io.FileNotFoundException ---编译时异常
		File file = new File("D:/test.txt");
		InputStream i = new FileInputStream(file);
	}
}

class Error {
	void test() {

	}
}

class Son extends Error {

}
  •  异常的捕获和处理

 * 异常处理:
 *     1.throw 制造异常,抛到上一层(方法中的异常,抛到方法上,在调用方法的时候还是要对该异常进行处理)
 *     2.处理异常的两种方式
 *         1.throw 抛出异常
 *         2.try...catch 捕获异常
 *             try{
 *                 可能会发生异常的代码
 *                 }catch(Exception e){
 *                     发生异常后会执行的代码
 *                 }finally{
 *                     一定会执行的代码
 *                 }
 * 
 * 注意:
 *         1.try中一旦发生异常,代码不会在继续执行下去,会直接执行对应的catch中的语句
 *         2.一个try后可以接一个或多个catch
 *         3.如果第一个catch世界收异常类型比较大的,后面的catch都是不可达语句

package day12;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionDemo3 {
	public static void main(String[] args) {
		File file = new File("D:/text.txt");
		try {
			FileInputStream is = new FileInputStream(file);
			System.out.println("文件存在....");
			String s = null;
			System.out.println(s.charAt(2));
			System.out.println("对象非null");
			int[] int1 = new int[3];
			System.out.println(int1[5]);
			System.out.println("索引正常使用");

		} catch (FileNotFoundException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (NullPointerException e) {
			System.out.println("空指针异常");
		} catch (Exception e) {
			System.out.println("哈哈哈");
			e.printStackTrace();
		} finally {
			System.out.println("一切搞定");
		}
	}
}
  •  运行期出现的错误

/*
 * 方法的重写 子类抛出异常类型 <= 父类类型
 */
class Fu {
	void test() throws Exception {

	}
}

class Zi extends Fu {
	@Override
	void test() throws NullPointerException {
		// TODO Auto-generated method stub
	}
}
  •  自定义异常

 * 自定义异常
 *         1.自定义的异常类要继承Exception
 *         2.自定义方法

public class ExceptionDemo4 {
	public static void main(String[] args) {
		Person p = new Person();
		p.setAge(-10);
	}
}

// 自定义异常
class IntegerException extends Exception {
	private int message;

	public IntegerException(int message) {
		this.message = message;
	}

	public String getMessage() {
		return "这个数字" + message + "不合法";
	}
}

class Person {
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		if (age > 0) {
			this.age = age;
		} else {
			System.out.println(new IntegerException(age).getMessage());
		}
	}

	public Person() {
		// TODO Auto-generated constructor stub
	}

}
  • 2.常用类

 *     如何学习常用类:
 *         1.构造器
 *         2.方法
 *             静态方法
 *             成员方法

  •  字符串相关类(String 、StringBuffer、StringBuilder)

 * String : 长度不可变的一个字符序列
 * StringBuffer : 长度可变,线程安全
 * StringBuilder : 长度可变,线程不安全
 * 记住一句话 ;一般线程安全的,效率就会底,不安全的效率高,一般我们挑选效率高的用

public class StringDemo5 {
	public static void main(String[] args) throws UnsupportedEncodingException {
		// String() 创建一个空字符序列
		String s1 = new String();
		System.out.println(s1);// ""

		// String(String origunal)
		String s2 = "123";
		String s3 = "123";
		System.out.println(s2 == s3);// true

		String s4 = new String("123");
		String s5 = new String("123");
		System.out.println(s4 == s5);// false
		System.out.println(s4.equals(s5));// true

		// String(byte[] bytes)根据字节数创建字符序列
		String s6 = new String(new byte[] { 66, 67 });
		System.out.println(s6);// BC

		// String(byte[] bytes, Charset charset)
		String s7 = new String(new byte[] { 66, 67 }, "utf-16");
		System.out.println(s7);// 䉃

		/*--很常用
		 * 5.String(byte[] bytes, int offset, int length) 
		 * 通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
		 * offset 开始位置
		 * length 个数
		 */
		String s8 = new String(new byte[] { 97, 98, 99, 100 }, 1, 2);
		System.out.println(s8);// bc

		// String(char[] value)根据字符组构造字符序列
		String s9 = new String(new char[] { '我', '是', '中', '国', '人' });
		System.out.println(s9);// 我是中国人

	}

}
  • String类常用方法

 1. char charAt(int index) 返回指定索引处的 char 值。
 2. int codePointAt(int index) 返回指定索引处的字符(Unicode 代码点)。 
 3.int codePointBefore(int index) 返回指定索引之前的字符(Unicode 代码点)。
 4.int compareTo(String anotherString) 按字典顺序比较两个字符串。等于返回0, >返回一个>0的数字, <返回一个<0的数字
 5.int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写
 6.String concat(String str) 将指定字符串连接到此字符串的结尾。
 7.boolean contains(CharSequence s) 当且仅当此字符串包含指定的 char 值序列时,返回 true。
 8.static String copyValueOf(char[] data)  返回表示参数字符数组的字符串
 9.static String copyValueOf(char[] data, int offset, int count)

/*
 * 常用方法
 */
public class StringDemo06 {
	public static void main(String[] args) throws UnsupportedEncodingException {
        String s=new String("shsxtverygood");
        //1. char charAt(int index) 返回指定索引处的 char 值。 
        char ch1=s.charAt(4);
        System.out.println("charAt(4):"+ch1);
        /*
         * 2. int codePointAt(int index) 
          	返回指定索引处的字符(Unicode 代码点)。 
         */
        int i=s.codePointAt(0);
        System.out.println("codePointAt(4)"+i);  //116
        
        /*
         * 3.int codePointBefore(int index) 
          		返回指定索引之前的字符(Unicode 代码点)。 
         */
        i=s.codePointBefore(5);
        System.out.println("codePointAt(5)"+i);
        
        /*
         * 4.int compareTo(String anotherString) 
          	按字典顺序比较两个字符串。 
          	等于返回0
          	>返回一个>0的数字
          	<返回一个<0的数字
         */
        i=s.compareTo("SHSXTVERYGOOD");
        System.out.println("compareTo(SHSXTVERYGOOD)"+i); //32  s=115  S=83  
        
        /*
         * 5.int compareToIgnoreCase(String str) 
          	按字典顺序比较两个字符串,不考虑大小写。 
         */
        i=s.compareToIgnoreCase("SHSXTVERYGOOD");
        System.out.println("compareToIgnoreCase(SHSXTVERYGOOD)"+i); //0 相等
        
        /*
         * 6.String concat(String str) 
          	将指定字符串连接到此字符串的结尾。 
         */
        String s2=s.concat("haha");
        System.out.println(s2);
        
        /*
         * 7.boolean contains(CharSequence s) 
          	当且仅当此字符串包含指定的 char 值序列时,返回 true。 
         */
        boolean b=s.contains("shsxt");
        System.out.println(b);  //true
        /*
         * 8.static String copyValueOf(char[] data)  返回表示参数字符数组的字符串
         */
        s2=String.copyValueOf(new char[]{'a','s','d'});
        System.out.println(s2);
        /*
         * 9.static String copyValueOf(char[] data, int offset, int count) 
         */
        s2=String.copyValueOf(new char[]{'a','s','d'},1,2);
        System.out.println(s2);
	}
}
package day12;

public class StringDemo7 {
	public static void main(String[] args) {
		String s = new String("you-and-me");
		String s1 = s.replace("you", "me");
		System.out.println(s1);// me-and-me

		// String[] split(String regex) 根据给定正则表达式的匹配拆分此字符串。
		String s2 = new String("you:zhangsan-me:lisi");
		String[] str = s2.split("-");
		for (String string : str) {
			str = string.split(":");
			System.out.println(str[1] + " ");
		}

		// String trim() 返回字符串的副本,忽略前导空白和尾部空白。
		String s3 = new String("  you:zhangsan  -  me:lisi   ");
		String s4 = s3.trim();
		System.out.println(s4);// you:zhangsan - me:lisi

		// static String valueOf(double d) 参数转为字符串 --系列重载方法
		System.out.println(String.valueOf(5.6).length());// 3
	}
}
  • 测试String 和StringBuffer是否操作的是原对象

package day12;

public class StringDemo8 {
	public static void main(String[] args) {
		StringBuffer ss1 = new StringBuffer("abc");
		System.out.println(ss1);
		StringBuffer ss2 = new StringBuffer(50);
		System.out.println(ss1.append("h哈哈哈"));
		System.out.println(ss1.delete(1, 3));
		System.out.println(ss1.insert(3, "刘文旭"));
		testString();
		testStringBuffer();
	}

	// 测试String 和StringBuffer是否操作的是原对象
	public static void testString() {
		String s1 = "haha";
		System.out.println(s1.hashCode());
		s1 += "hehe";
		System.out.println(s1.hashCode());
	}

	public static void testStringBuffer() {
		StringBuffer s = new StringBuffer("abc");
		System.out.println(s.hashCode());
		s.append("cde");
		System.out.println(s.hashCode());
	}
}
  •  算法及数组工具类(Arrays)

            见第十一天数组部分

  •  日期类

 * 日期类  Date
 *     构造器:
 *         Date()  
 *         Date(long time)
 *  注意:
 *      Date-->java.util.Date
 *      从1970.1.1日开始计算日期

public class DateDemo10 {
	public static void main(String[] args) {
		/*
		 *  Date()   以当前时间我准创建日期对象
 * 			Date(long time) 是以毫秒数为准计算创建一个日期对象
		 */
		Date d1=new Date();
		System.out.println(d1);
		Date d2=new Date(1535189761147l);
		System.out.println(d2);
		
		/*
		 * 获取当前毫秒数 getTime()     1s=1000ms
		 */
		long l=d1.getTime();
		System.out.println(l);
		
		/*
		 * 比较日期的大小
		 * 	1.equals() 比较两个日期是否为同一时间对象
		 * 	2.before() 当前时间是否在比较日期之前	
		 * 	3.after() 当前时间是否在比较日期之后
		 * 	4.compareTo() 比较两个日期是否相等
		 * 		相等返回0
		 * 		>返回1的值
		 * 		<返回-1的值
		 */
		Date date1=new Date();
		Date date2=new Date();
		Date date3=new Date(1232145545232l);
		System.out.println(date1.equals(date2));
		System.out.println(date1.before(date3));
		System.out.println(date1.after(date3));
		System.out.println(date2.compareTo(date1));
		/*
		 * setTime() 
		 *  0 回到1970年1月1日 8点
		 */
		date1.setTime(0);
		System.out.println(date1);
		
		//返回当前系统毫秒数
		System.out.println(System.currentTimeMillis());
	}
}
  • SimpleDateFormat

 * SimpleDateFormat 转换类|格式类
 *     
 *   y    年
 *  M    月
 *  d     日
 *  H    时     24小时制
 *  h     时    12小时制
 *  m    分
 *  s     秒
 *  S    毫秒

public class SimpleDateFormatDemo11 {
	public static void main(String[] args) throws ParseException {
		Date date=new Date();
		System.out.println(date);
		SimpleDateFormat s=new SimpleDateFormat();
		/*
		 * format()  把一个日期类型转换为一个字符串类型
		 * parse()	 把一个日期格式的一个字符串转换为一个日期类型
		 */
		System.out.println(s.format(date));  //18-8-25 下午5:59
		
		SimpleDateFormat s1=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss SSS");
		System.out.println(s1.format(date));
		
		String str="2018-08-08 12:12:12";
		SimpleDateFormat s2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(s2.parse(str));
	}
}
  •  基本数据类型包装类

 * 基本类型
 *     int --- Integer
 *     byte --- Byte
 *     short--- Short
 *  long --- Long
 *  folat --- Float
 *  double --- Double
 *  char --- Character
 *  boolean --- Boolean
 * 
 *  自动装箱:从基本数据类型转为包装类型
 *  自动拆箱:从保证类型转为基本数据类型

public class IntegerDemo09 {
	public static void main(String[] args) {
		Integer i=123; //自动装箱  Integer.valueOf(123)
		int i2=i;   //自动拆箱   Integer.inValue(i)
		
		Double d=5.5; //Double.valueOf(5.5)
		double d1=d;  //自动拆箱   Double.inValue(i)
		
		int i4=123;
		int i3=123;
		System.out.println(i4==i3);  //true
		Integer i5=123;
		System.out.println(i==i5);  //true
		System.out.println(i5==i4); //true
		
		Integer i6=127;
		Integer i7=127;
		System.out.println(i6==i7);  //false
		
	}
}
  •  Math类

public class MathDemo12 {
	public static void main(String[] args) {
		double d = 1.4;
		// static double floor(double a)--向下取整
		System.out.println(Math.floor(d));
		// static double ceil(double a) --向上取整
		System.out.println(Math.ceil(d));
		// static double round(double a)--四舍五入
		System.out.println(Math.round(d));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值