Java 异常处理机制 -18天 学习笔记

异常处理的5个关键字

try,catch,finally,throw,throws
使用异常处理机制是为了可以让程序完整运行,因为一旦出现异常,程序就会自己终止。

抛出异常

package com.oop.Demo05;

public class Text1
{
		public static void main (String[] args){
				
		try
		{
		new Text1().add(1,0);
		}
		catch (ArrayStoreException e) {}

			
		}
		//一般在方法上throws,throws就必须要捕获异常try 加catch
		public void add (int a ,int b)throws ArrayStoreException{
				if(a==0 && b==0){//主动抛出异常 一般在方法中throw
	
				throw new ArrayStoreException();
		   
				}
					System.out.println(a/b);
		}
}

捕获异常

package com.oop.Demo05;

public class Text
{
		public static void main (String[] args){
				
						int a = 1;
	
						int b = 0;
						
						try{  //监控区域
								System.out.println(a/b);
			 		}catch(ArithmeticException e){//catch 捕获这个异常命名为e
								System.out.println("程序出现异常,变量b不能为0");
						}finally{//finally 处理善后工作,无论异常不异常最后都会出现finally
								System.out.println("Finally");
						}
						//try{ }catch(){}是必须要的东西
						//finally 一般用于io 资源关闭
							//	System.out.println(a/b);
				
								//出现异常
					try{
							new Text().a();
					}catch(Error e){
							//可以加多个catch  前提必须要从小往大
							System.out.println("Error");
					}catch(Exception e){
							System.out.println("Exception");
					}
					catch(Throwable e){  //catch(想要捕捉的类型)
					System.out.println("Throwable");
							
					}//输出error 说明是error错误
								
								
					//也可以使用快捷键 Ctrl + alt +t
								
						}
						
						
						
		  public void a(){//递归
						b();
				}
				public void b(){
						a();
				}
		
     
		
		
		
}

实际应用中的经验总结‘

  • 处理运行中的异常时,采用合理规避同时辅助try-catch
  • 在多重catch块后面,可以加catch(Exception)来处理可能会被遗漏的异常
  • 对应不确定的代码,也可以加上try-catch,处理潜在的异常
  • 尽量去处理异常,切记质数简单调用printStackTrace()去打印输出
  • 具体如何处理异常,要根据不同的义务需求和异常类型去决定
  • 经理添加finally语句块去释放占用的资源。

猜你喜欢

转载自blog.csdn.net/yibai_/article/details/114993314