JavaSE自学笔记Real_005
异常(Exception)
软件在运行过程中,非常可能遇到各种异常问题,英文是:Exception,意思时例外,这些例外情况,或者叫异常。
异常值程序运行中出现的不期而至的各种状况,如文件不到,网络连接失败,非法参数等
异常常发生在程序运行期间,它影响了正常的程序执行流程
常用异常处理关键字
try catch finally throw throws
//异常关键字:try catch finally throw throws
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要补货多个异常们需要从小到大的去捕获
//快捷键:选中要进行捕捉错误的代码,按Alt+Ctrl+T键就可以极性选择
try{ //try:监控区域
System.out.print(a/b);
}catch(ArithmeticException e) { //catch:捕捉异常 可以进行多个错误的捕获
System.out.println("程序出现异常,变量b不能为0");
}finally{ //处理善后工作 一般用于关闭一些正在占用内存的资源,如Scanner等
System.out.println("Finally");
}
}
//throws用于在生命方法时抛出异常,假设这个方法处理不了这个异常,就在方法上抛出异常
public void test001(int a, int b) throws ArithmeticException{
if(b == 0){
throw new ArithmeticException();//throw : 主动抛出异常,一般在方法中使用
}
}
}
自己制作异常
public class TestCode {
//可能会存在异常的方法
static void test(int a) throws MyException{
System.out.println("传递的参数为" + a);
if(a>10){
throw new MyException(a); //抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try{
test(100);
}catch(MyException e){
System.out.println("MyException=>" + e);
}
}
}
//=============================================================
//自己定义的异常只需要继承Exception类就可以了
public class MyException extends Exception{
//传递的数字大于10就报错;
private int detail;
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public MyException(int a) {
this.detail = a;
}
//toString:用于出现异常时打印信息
/**
* Returns a short description of this throwable.
* The result is the concatenation of:
* <ul>
* <li> the {@linkplain Class#getName() name} of the class of this object
* <li> ": " (a colon and a space)
* <li> the result of invoking this object's {@link #getLocalizedMessage}
* method
* </ul>
* If {@code getLocalizedMessage} returns {@code null}, then just
* the class name is returned.
*
* @return a string representation of this throwable.
*/
@Override
public String toString() {
return "MyException{" + detail + "}";
}
}
实际应用中的总结
1、处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
2、在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
3、对于不确定的代码,也可以加上try-catch,处理潜在异常
4、尽量去处理异常,切忌只是简单的调用printStackTrace()去打印输出
5、具体如何处理异常,要根据业务不同的需求和异常类型去决定
6、尽量添加finally语句块去始放占用的资源