五个常见异常的案例

1.算术异常:ArithmeticException
2.字符索引越界异常:ArrayIndexOutOfBoundsException
3.空指针异常:NullPointerException
4.正则表达式语法异常:PatternSyntaxException
5.数组为负异常:NegativeArraySizeException

public class Work03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			int i=3/0;
			System.out.println(i);
		} catch(ArithmeticException e) {
			System.out.println("算术异常!");
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		System.out.println("运行1");
		int[] arrInt= {1,5,8,4,3};
		try {
			System.out.println(arrInt[5]);
		} catch (ArrayIndexOutOfBoundsException e) {
			// TODO Auto-generated catch block
			System.out.println("字符索引越界异常");
		}
		
		System.out.println("运行2");
		String str=null;
		try {
			if(str.equals("test")) {
				System.out.println("哈哈");
			}
		}catch(NullPointerException e) {
			System.out.println("空指针异常!");
		}
		
		System.out.println("运行3");
		String str01="账号:asd1234 密码:asAZddefe"
		+"账号:safg134534 密码:asAZddefe"
		+"账号:1646465df 密码:asAZddefe";
		try {
			Pattern p=Pattern.compile("账号:[a-z0-9]{6-16} 密码:[0-9a-zA-Z]{6,19}");
			Matcher m=p.matcher(str01);
			while(m.find()) {
				System.out.println(m.group());
			}
		} catch (PatternSyntaxException e) {
			System.out.println("语法异常");
			
		}
		System.out.println("运行4");
		try {
			char[] ch=new char[-1];
		} catch (NegativeArraySizeException e) {
			// TODO Auto-generated catch block
			System.out.println("负数组异常");
		}
		
		System.out.println("运行5");
		
       
	}

}

你可能感兴趣的:(Java)