Java exception handling mechanism-18 days study notes

5 keywords for exception handling

Try, catch, finally, throw, throws
use the exception handling mechanism to allow the program to run completely, because once an exception occurs, the program will terminate by itself.

Throw an exception

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);
		}
}

Catch exception

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();
				}
		
     
		
		
		
}

Summary of experience in practical application'

  • When dealing with abnormalities in operation, adopt reasonable evasion and assist try-catch at the same time
  • After multiple catch blocks, catch (Exception) can be added to handle exceptions that may be missed
  • Corresponding to uncertain code, try-catch can also be added to handle potential exceptions
  • Try to handle exceptions as much as possible, remember the prime numbers and simply call printStackTrace() to print the output
  • How to deal with exceptions should be determined according to different obligation requirements and exception types
  • The manager adds a finally block to release the occupied resources.

Guess you like

Origin blog.csdn.net/yibai_/article/details/114993314