java____异常概述、理解

异常机制Exception

  • 异常指程序运行中出现的不期而至的各种状况,如文件找不到、网络连接失败、非法参数等等。
  • 异常发生在程序运行期间,它影响了正常的程序执行流程
public class Test {
     
	public static void main(String[] args) {
     
		System.out.println(11/0);
		//Exception in thread "main" java.lang.ArithmeticException: / by zero
	}
}

java____异常概述、理解_第1张图片

java____异常概述、理解_第2张图片

异常处理机制

  • 抛出异常
  • 捕获异常

异常处理五个关键字

  1. try
  2. catch
  3. finally
  4. throw
  5. throws
public class Test {
     
	public static void main(String[] args) {
     
		int a = 1;
		int b = 0;
		//捕获多个异常 从小到大!
		try {
     
			System.out.println(a / b);
		} catch (Error e) {
     
			System.out.println("程序出现异常,变量b不能为0---Error");
		} catch (Exception e) {
     
			System.out.println("程序出现异常,变量b不能为0---Exception");
		} catch (Throwable e) {
     
			System.out.println("程序出现异常,变量b不能为0---Throwable");
		}finally {
     
			System.out.println("我都执行嗷");
		}
		//finally 可以不要 常用于资源关闭
	}
}


//eclipse  快捷键 右键->Surround With
//idea 	   快捷键 ctrl +alt+T

throw、throws

public class test1 {
     
	public static void main(String[] args) {
     
		new test1().add(1, 0);
	}
	//假設这方法中,处理不了这个异常,方法上抛出异常
	public void add(int a, int b) throws ArithmeticException{
     
		if (b == 0) {
     
			throw new ArithmeticException();
		}
	}
}

自定义异常(了解)

java____异常概述、理解_第3张图片


实际应用中的经验总结

java____异常概述、理解_第4张图片

你可能感兴趣的:(Java,java)