异常|常用类

异常

  • Error:错误:一般是由虚拟机生成并脱出的,程序员无法解决

  • Exception: 异常
    CheckException 编译时异常: 编译时期就会出现的异常 ,如果出现了编译时异常不处理,程序无法运行
    RuntimeException 运行时异常 : 运行时期会出现的异常 ,所有的运行时异常都会直接或者间接的继承自RuntimeException,可通过增强程序的健壮性处理 if判断

    常见的运行时异常:
    1.空指针异常 java.lang.nullpointerexception
    简单地说就是调用了未经初始化的对象或者是不存在的对象,这个错误经常出现在创建图片,调用数组这些操作中,比如图片未经初始化,或者图片创建时的路径错误等等。
    2. java.lang.classnotfoundexception
      这个异常是很多原本在jb等开发环境中开发的程序员,把jb下的程序包放在wtk下编译经常出现的问题,异常的解释是"指定的类不存在",这里主要考虑一下类的名称和路径是否正确即可,如果是在jb下做的程序包,一般都是默认加上package的,所以转到wtk下后要注意把package的路径加上。
      3. java.lang.arithmeticexception
      这个异常的解释是"数学运算异常",比如程序中出现了除以零这样的运算就会出这样的异常,对这种异常,大家就要好好检查一下自己程序中涉及到数学运算的地方,公式是不是有不妥了。
      4. java.lang.arrayindexoutofboundsexception
      这个异常相信很多朋友也经常遇到过,异常的解释是"数组下标越界",现在程序中大多都有对数组的操作,因此在调用数组的时候一定要认真检查,看自己调用的下标是不是超出了数组的范围,一般来说,显示(即直接用常数当下标)调用不太容易出这样的错,但隐式(即用变量表示下标)调用就经常出错了,还有一种情况,是程序中定义的数组的长度是通过某些特定方法决定的,不是事先声明的,这个时候,最好先查看一下数组的length,以免出现这个异常。
      5. java.lang.illegalargumentexception
      这个异常的解释是"方法的参数错误",很多j2me的类库中的方法在一些情况下都会引发这样的错误,比如音量调节方法中的音量参数如果写成负数就会出现这个异常,再比如g.setcolor(int red,int green,int blue)这个方法中的三个值,如果有超过255的也会出现这个异常,因此一旦发现这个异常,我们要做的,就是赶紧去检查一下方法调用中的参数传递是不是出现了错误。
      6. java.lang.illegalaccessexception
      这个异常的解释是"没有访问权限",当应用程序要调用一个类,但当前的方法即没有对该类的访问权限便会出现这个异常。对程序中用了package的情况下要注意这个异常。

算术异常类:ArithmeticExecption

空指针异常类:NullPointerException

类型强制转换异常:ClassCastException

数组负下标异常:NegativeArrayException

数组下标越界异常:ArrayIndexOutOfBoundsException

违背安全原则异常:SecturityException

文件已结束异常:EOFException

文件未找到异常:FileNotFoundException

字符串转换为数字异常:NumberFormatException

操作数据库异常:SQLException

输入输出异常:IOException

方法未找到异常:NoSuchMethodException


throw 制造异常

throws 异常抛出 ***

try…catch 异常捕获 ***

   	try{
   		可会出现异常的代码...
   	}catch(NullPointerException e){
   		如果出现这个异常,需要执行的代码
   	}catch(FileNotFoundException e){
   	 ...
   	}catch(Exception e){
   	 ...
   	}
   	...
   	finally{
   		无论是否出现异常,都会执行的代码
   	}

try中一旦出现异常,不会继续向下执行,会执行对应的catch中的内容
一个try中可以跟1~多个 catch,小范围catch放在放在上面,大范围的catch放下面

运行时异常可以使用增强程序的健壮性或者异常处理方式的两种,抛出或者捕获处理
编译时异常必须使用异常处理方式的两种,抛出或者捕获处理

	public class ExceptionDemo02 {
		public static void main(String[] args) {
			/*String str1=null;
			str1.charAt(1);*/
			
			try {
				//InputStream is=new FileInputStream("D:/text.txt");
				String str=null;
				//str.charAt(1);
				System.out.println("try结束了");
			} /*catch (FileNotFoundException e) {
				e.printStackTrace();
				System.out.println("文件未找到");
			}*/ catch (Exception e) {
				e.printStackTrace();
			} finally{
				System.out.println("最后的最后...");
			}
			
			System.out.println("try..catch结束了");
			
			test(5);
		}
	
		static void test(int a){
			//手动制造异常
			//throw new NullPointerException();
			//System.out.println("test------------");
			
			try{
				if(a==5){
					return;
				}
			}catch(Exception e){
				
			}finally{
				System.out.println("haha");
			}
		}
	}
	
	/*
	 * 重写方法抛出异常问题: 子类小于等于父类
	*/
	class Fu{
		void haha() throws Exception{}
	}
	
	class Zi extends Fu{
		void haha() throws FileNotFoundException{}
	}

自定义异常

现在使用的都是java提供的异常类,可以自定义异常类
自定义的异常类必须直接或者间接的继承自Exception类

public class DefinedException03 {
	public static void main(String[] args) {
		Person p =new Person();
		p.setName("双双");
		int age=-10;
		/*if(age>0 && age<150){
			p.setAge(age);
		}else{
			p.setAge(18);
		}*/
		
		try {
			p.setAge(-11);
		} catch (AgeException e) {
			e.printStackTrace();
		}
		
		System.out.println(p);
	}
}

//自定义异常类  年龄不合法异常,在出现年龄<=0或者年龄>=150时候出现
class AgeException extends Exception{
	public AgeException() {
		// TODO Auto-generated constructor stub
	}
	
	public AgeException(int age) {
		super(age+"岁年龄不合法");
	}
}

class Person{
	private String name;
	private int age;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws AgeException {
		if(age>0 && age<150){
			this.age = age;
		}else{
			//System.out.println("年龄不合法");
			throw new AgeException(age);
		}
	}

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

常用类

字符串 String :

不可变长的字符序列 ,Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。

  • String : 不可变长的字符序列

  • StringBuilder : 可变长的字符序列 ,线程不安全,效率高

  • StringBuffer : 可变长的字符序列 , 线程安全的,效率较低 是字符数组形式存储的

     public class StringDemo02 {
     	public static void main(String[] args) throws UnsupportedEncodingException {
     		//空串
     		String str1=new String();
     		System.out.println(str1.length());
     		
     		//字符数组转为字符串
     		//static String copyValueOf(char[] data) 
     		//String(char[] value)    分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
     		char[] ch=new char[]{'a','b','c','d','e','f'};
     		String str2=new String(ch);
     		System.out.println(str2);
     		
     		//String(char[] value, int offset, int count)  分配一个新的 String,它包含取自字符数组参数一个子数组的字符。
     		String str3=new String(ch,2,3);
     		System.out.println(str3);
     		
     		//String(String original) 
     		String str4=new String("abc");
     		System.out.println(str4);
     		
     		byte[] arr="因为你好".getBytes("gbk");
     		//String(byte[] bytes)   平台默认
     		String str5=new String(arr);
     		System.out.println(str5);
     		System.out.println(Arrays.toString(arr));
     		
     		//String(byte[] bytes, String charsetName)  通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
     		String str6=new String(arr,"gbk");
     		System.out.println(str6);
     		
     		//String(byte[] bytes, int offset, int length, String charsetName) 
     		String str7=new String(arr,2,4,"gbk");
     		System.out.println(str7);
     		
     		//char charAt(int index) 返回指定索引处的 char 值。 
     		System.out.println(str6.charAt(2));
     		
     		// int compareTo(String anotherString)  按字典顺序比较两个字符串。 
     		System.out.println("ab".compareTo("A")); //32
     		
     		// String concat(String str)将指定字符串连接到此字符串的结尾。 
     		System.out.println(str6.concat("哈哈"));
     		//boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结束。 
     		System.out.println(str6.concat("哈哈"));
     		
     		// boolean contains(CharSequence s) 当且仅当此字符串包含指定的 char 值序列时,返回 true。
     		System.out.println(str6.contains("你好"));
     		
     		//byte[] getBytes()  
     		//byte[] getBytes(String charsetName)  
     		System.out.println(str6.getBytes());
     		
     		//void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)  将字符从此字符串复制到目标字符数组。 
     		char[] c=new char[5];
     		str6.getChars(0, 4, c, 1);  //结束位置不包含
     		System.out.println(c);
     		
     		//int indexOf(String str) 
     		System.out.println("abcababc".indexOf('a'));
     		System.out.println("abcababc".lastIndexOf('a'));
     		
     		//String replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 
     		String s="  abca babc  ";
     		System.out.println(s.replace('a', 'A'));
     		
     		// String[] split(String regex) 
     		 String ss="name=zhangsan";
     		 System.out.println(Arrays.toString(ss.split("=")));
     		 
     		 //String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。 
     		 //String substring(int beginIndex, int endIndex)  endIndex结束位置索引不包含
     		 System.out.println(s.substring(5));
     		 System.out.println(s.substring(3,5));
     		 //char[] toCharArray()   将此字符串转换为一个新的字符数组。 
     		 System.out.println(s.toCharArray());
     		 
     		 //String toLowerCase() 
     		 // String trim() 返回字符串的副本,忽略前导空白和尾部空白 
     		 System.out.println(s.trim());
     		 
     		 //valueOf(参数) 任意类型参数转为字符串
     
     	}
     }
    
  • StringBuilder:单线程环境下大量操作字符串,效率较高

  • StringBuffer : 多线程环境系大量操作字符串,线程安全,同步

  • String : 表示少量操作字符串 ,简单,功能较多

  • 可以相互转换

      public class StringDemo03 {
     	public static void main(String[] args) {
     		//StringBuilder(String str)
     		StringBuilder sb=new StringBuilder("haha");  //默认16大小
     		System.out.println(sb);
     		//int capacity() 
     		 // length()
     		System.out.println(sb.capacity());
     		System.out.println(sb.length());
     		
     		//重点方法:
     		//StringBuilder append(int i)   追加
     		StringBuilder s=sb.append(true);
     		System.out.println(sb);
     		System.out.println(sb==s);
     		
     		// StringBuilder delete(int start, int end)   end不包含 删除
     		System.out.println(sb.delete(4, 6));
     		
     		//StringBuilder insert(int offset, char c)   插入
     		System.out.println(sb.insert(3, 123));
     		
     		 //StringBuilder reverse()  翻转
     		System.out.println(sb.reverse());
     		
     		String str="abcdef";
     		char[] arr=str.toCharArray();
     		System.out.println(Arrays.toString(arr));
     		String str2="";
     		for(int i=arr.length-1;i>=0;i--){
     			str2+=arr[i];
     		}
     		System.out.println(str2);
     		
     		String str3=new String(sb);
     		System.out.println(str3);
     	}
     }
    

Math 数学工具类

public class MathDemo {
	public static void main(String[] args) {
		//static double ceil(double a) 向上取整
		System.out.println(Math.ceil(-3.9));
		//static double floor(double a) 向下取整
		System.out.println(Math.floor(-3.9));
		
		//static long max(long a, long b)  返回两个 long 值中较大的一个。 
		//static double min(double a, double b)  
		System.out.println(Math.max(-3.9,9.9));
		System.out.println(Math.min(-3.9,9.9));
	}
}

枚举类

使用enum关键字定义枚举
表示一种事物的多种可能|所有可能|所有情况
注意:
所有的枚举类都隐式继承自java.lang.Enum类
枚举中的所有成员|实例|字段 都是,默认public static final,都是当前类型的一个实例

	public class Employee {
	private int id;
	private String name;
	private Status status;
	
	public Employee() {
		// TODO Auto-generated constructor stub
	}

	public Employee(int id, String name, Status status) {
		super();
		this.id = id;
		this.name = name;
		this.status = status;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public Status getStatus() {
		return status;
	}

	public void setStatus(Status status) {
		this.status = status;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", status=" + status + "]";
	}
	
}

//状态   A,B,C,D,E 从忙到闲
enum Status{
	A,
	B,
	C,
	D,
	E;
}
//主方法
	public class Test {
	public static void main(String[] args) {
		Employee emp1=new Employee();
		emp1.setId(8888);
		
		emp1.setName("员工1");
		emp1.setStatus(Status.A);
		
		Employee emp2=new Employee(9999,"lisi",Status.B);
		Employee emp3=new Employee(10000,"员工2",Status.E);
		Employee emp4=new Employee(10001,"员工3",Status.A);
		
		Employee[] arr={emp1,emp2,emp3,emp4};
		
		//给公司最忙员工放假三天
		for(Employee emp:arr){
			switch(emp.getStatus()){
			case A:
				System.out.println(emp.getName()+"放假三天!!!!");
				break;
			default:
				System.out.println(emp.getName()+"努力加班,期待下一次放假!!!");
				break;
			}
		}
	}
}

包装类型: 基本数据类型的包装类

基本数据类型 包装类

  • byte — Byte
  • short — Short
  • int — Integer
  • long — Long
  • float — Float
  • double— Double
  • char — Character
  • boolean — Boolean

转换:
自动装箱: 基本—>包装
自动拆箱: 包装—>基本

public class DataDemo01 extends Object{
	public static void main(String[] args) {
		Integer i1=121;  //自动装箱  Integer.valueOf(121)
		Integer i2=1;
		System.out.println(i1+i2);  //自动拆箱
		int i3=i1;   //自动拆箱  i1.intValue() 
		
		test(2.2,1.1);
		
		System.out.println(Integer.parseInt("123"));
		System.out.println(Integer.reverse(12));
	}
	
	static void test(Double d1,Double d2){
		System.out.println(d1-d2);
	}
}

	//2

	public class DataDemo02 {
		public static void main(String[] args) {
			int i1=121;
			Integer i2=121;  //Integer.valueOf(121)  缓冲区对象 -128~127 之外返回new Integer,之内返回缓冲区对象
			Integer i3=121;
			Integer i4=128;
			Integer i5=128;
			
			Integer i6=new Integer(121);
			Integer i7=new Integer(121);
			
			System.out.println(i1==i2);  //true  自动拆箱
			System.out.println(i2==i3);  //true  
			System.out.println(i4==i5);  //false  
			System.out.println(i2==i6);  //false  
			System.out.println(i7==i6);  //false  
			
			String str1="abc";  //字符串常量池里
			String str2=new String("abc");  //堆中的地址
			System.out.println(str1==str2); //false
			
			/*
			 * 总结:
			 * 	1.如果两个new Integer比较是否相等,肯定不相等,堆中的两个地址
			 * 	2.如果一个Integer,一个new Integer肯定不相等,一个常量池,一个堆中的地址,肯定不相等
			 * 	3.如果int与Integer|new Integer 都会发生自动拆箱,值相等就相等
			 * 	4.如果是两个Integer,判断值是否在[-128,127]之间,之间就相等,否则不等
			 */
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值