Java异常--try catch finally,throw ,throws

public class Demo1 {  
private Demo1 demo1;
	
	public Demo1() {
        //会出现栈溢出错误,死循环
		demo1 = new Demo1();
	}
	}

异常的执行情况,及异常跟踪演示。

当异常没有try{} catch(){},会报异常并终止程序运行,当用try{} catch(){}时,会报异常程序继续执行。

public class Demo2 {
	public static void main(String[] args) {
		TestClass t = new TestClass();
		t.test();
	}
}
class TestClass{
	public void test() {
		int[] num = new int[5];  // num[0] 1,2,3,4 
		System.out.println(num[num.length - 1]); // num[5]时会出现运行时异常( );运行时异常可以处理也可不处理。
		
        //num[5]出现异常下面代码不会执行
		int a = 1;
		int b = 2;
		System.out.println(a + b);
		
		// 检测异常/ 非运行时异常 / 编译时异常    / 需要我们处理。
		File f = new File("c://hh.txt");//输入的path正确,可以在创建一个 txt类型的文件
		try { 
			f.createNewFile();
		} catch (IOException e) {//根据错误的类型尽量缩小范围
			e.printStackTrace();
		}// try之后,并没有终止程序。接着执行。
		
		int x = 1;
		int y = 2;
		System.out.println(x + y);
		
	}
}

 如何处理Exception异常
 * 处理异常的方式:抓抛模型
 * 1.抛:当执行程序时,一旦出现异常,就会生成一个对应异常类型的对象,并将对象抛出
 *   ①.抛的类型:自动抛和手动抛
 *   ②.此异常的对象将来是交给方法的调用者
 * 2.抓:抓住程序中抛出来的异常对象。
 *   异常处理的方式:
 *   1.try-catch-finally
 *   try{
 *      //可能会发生异常的代码 
 *   }catch(Exception e1){
 *     // 处理方式一
 *   }catch(Exception e2){
 *     //处理方式二 
 *   }finally{
 *       // 一定会执行的代码
 *   }
 *   ①.try代码块里面的声明的变量,是局部变量,作用域是在代码块中
 *   ②.finally是可选的,如果加了finally,不论是否出现异常,都会执行finally中代码
 *   ③.catch语句是用来处理异常 
 *     getMessage();printStrackTrace():打印异常信息(程序出错的位置信息及原因)
 *   ④.catch代码块可以有多个,try中抛出的异常对象是从上往下去匹配catch中的异常类型,一旦满足就行
 *     catch中的代码。执行完毕,就跳出所有的catch。
 *   ⑤.如果catch中多个异常类型是并列关系,不需要考虑顺序问题。
 *     如果catch中多个异常类型有继承关系,子类需要在父类异常对象的上面。
 *   ⑥.try-catch是可以嵌套多层。

*catch中的异常处理与try中的异常不匹配时,就相当于没有try catch,程序会报错。
 * 提示: 
 *  1、对于运行时异常,可以不用显示的进行异常处理。除了RuntimeExpetion及子类之外的异常都是编译异常,都需要通过try()或throws抛出的方式处理。
 *  2、对于编译时异常,必须要显示的进行异常处理。
 * 

检测异常处理

		File file = null;
                try {
			file = new File("xxxx");
			file.createNewFile();
			Class.forName("");//这个地方会出现异常try下面的语句不在执行,直接跳转到catch
			Thread.sleep(124);
		}catch(IOException e) {
			e.printStackTrace();
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		
        
        //上面的简化
		try {
			file = new File("xxxx");
			file.createNewFile();
			Class.forName("");
			Thread.sleep(124);
		}catch(Exception e) {//Exception是所有异常的父类
			e.printStackTrace();
		}
		

常出现的异常

类型转换异常

	// 类型转换异常  ClassCastExcetion
	public static void test1() {
		
		Object object = LocalDateTime.now();
		String str = "";
		str = (String)object;
	}

空指针异常 

// 空指针异常  NUllpointerExcetion
	public static void test2() {
		List s = getList();
		if(s != null)//不加判断会报空指针异常 
        {
			System.out.println(s.size());		
		}
	}
	public static List getList() {
		//
		List l = new ArrayList<String>();
		l.add("a");
		
		return null;//这个地方没有返回值。
	}

 

算术异常

 

//	 2,算术异常  12/ 0 
	public static  void test() {
		
		int i = 12;
		try {
			System.out.println(i / 0);//除数为零
		}catch (ArithmeticException e) {
			e.printStackTrace();
		}
		System.out.println("sssssssssss");
	}
	

 

try catch finally,注意有return时的使用情况

jdbc中的数据

a=b
c=3


 

public class Demo2 {
	public static void main(String[] args) {
		
		InputStream s = null;
		try {
			s = Demo2.class.getClassLoader().getResourceAsStream("jdbc");
			Properties p = new Properties();
			p.load(s);
			
		}catch(IOException e) {
			e.printStackTrace();
		}catch(Exception e) {
			
		} finally {//一般情况下finally都会执行,除了极端的情况(如断电)。
			try {
				s.close();//释放资源
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		
		
		System.out.println("end");
		
		int i =test();
        System.out.println(i);//输出一下test返回的值
		
	}
	
	public static int test() {
		try {
			int s = 10 / 0;
			System.out.println("3=====");
			return 10;
		}catch (Exception e) {
			
		}finally {
			System.out.println("1=====");
		}
		System.out.println("2=====");

		return 0;
	}
	
}

test()中的执行顺序:try -> int s=10/0; -> catch->Exception e ->finally块中的语句 ->输出语句"2======" -> return 0->test();

除数不为零时的执行顺序:try -> int s=10/0; -> 输出语句"3=====" ->finally块中的语句 ->return 10 ->test();

 

IOException检测异常可以自己解决通过try,也可以抛给别人(调用这个方法的函数)

	public static void test() throws FileNotFoundException{//直接抛出异常
		FileInputStream input = new FileInputStream(new File("xx"));
		
	}
	
	public static void test1() {
		try {//自己解决异常处理
			FileInputStream input = new FileInputStream(new File("xx"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

将检测异常转化为运行时异常

	// 把检测异常转换为运行时异常。
	public static void test3() throws MyRunTimeException {
		try {
			FileInputStream input = new FileInputStream(new File("xx"));
		} catch (FileNotFoundException e) {
			throw new MyRunTimeException("文件不存在,需要观察一下文件目录。");
		} 
		
		try(FileInputStream input = new FileInputStream(new File("xx"))){
			
		}catch (Exception e) {
			
		}
	}
	
    class MyRunTimeException extends RuntimeException{//继承RuntimeException
	    public MyRunTimeException(String s) {
		super(s);//用父类的构造方法
	    }
    }
// 运行时异常。
	public static void test2() throws ArithmeticException{
		try {
			int x = 12 / 0;
		}catch (ArithmeticException e) {
			// 自己处理
			e.printStackTrace();
			// throw
			throw new ArithmeticException();
		}
		System.out.println("end");
		// 可处理也可不处理,因为test3的异常时运行时异常
		test3();
	}

/**
* 异常处理的方式一:try-catch-finally(自行处理)
* 异常处理的方式二:在方法的声明处,显示的抛出异常的对应类型(委托处理)
* 格式:public void method() throws IoException,FileNotFoundException
* ①.当此方法内部出现异常时,会抛出一个异常类的对象,抛给方法的调用者
* ②.异常对象可以一直向上抛,直到Main函数,也可以通过try-catch进行处理异常。
*    
*/

public class Demo2 {
	
	public static void main(String[] args) {
		try {
			m2();
		} catch (MyException e) {
			e.printStackTrace();//异常信息的打印
		}
	}
	
	public static void m4() throws MyException{
		int x = 1;
		int b = 2;
		if(x > b){//断言
			throw new MyException("出现错误");
		}
	}
	
	public static void m2() throws MyException{
		try {
			m1();
		} catch (IOException e) {
			e.printStackTrace();
			throw new MyException("反生了io异常");
		} 
		
	}
	
	public static void m1() throws IOException,FileNotFoundException {
		FileInputStream f = new FileInputStream("xx");
		f.close();
	}
}

class MyException extends Exception{
	public MyException() {}
	public MyException(String mes) {
		super(mes);
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值