当前位置:网站首页>异常处理4种方法
异常处理4种方法
2022-06-28 09:21:00 【用户9857551】
异常处理4种方法
throw关键字:可以在指定方法中抛出指定异常。 使用格式:throw new xxxException(“异常产生的原因”); 注意: 1.throw关键字必须写在方法内部。 2.throw关键字后边的new对象必须是Exception或者是Exception的子类对象。 3.throw关键字抛出指定的异常对象,我们就必须处理。 throw关键字后边是RuntimeException或是RuntimeException的子类对象,我们就可以不处理,默认交给JVM处理(打印异常,中断处理)。 throw关键字后边是编译异常(写代码报错),我们必须处理这个异常,要么throws要么try-catch。
1.throws使用
修饰符 返回值类型 方法名(参数列表)throw xxxException...{
throw new xxxException("产生原因");
throw new xxxException("产生原因");
}如果还有后续代码,就用到try-catch,在try-catch外边写。
2.try-catch
格式:
try{
可能产生异常的代码
}catch(定义一个异常的变量,用来接收try中抛出来的异常对象){
异常的处理逻辑,异常之后怎么处理异常对象
一般会记录在日志中
}
......
catch(异常类名 变量名){
}注意: 1.try可能抛出多个异常,可以多个catch处理 2.产生异常catch处理完了,继续进行下边的代码。如果没有异常不执行catch,继续下边的代码。
3.Throwable类
这个类下边有三个方法
4.finally代码块
这个代码块不能单独使用,是和try-catch一块用的,一般用于资源回收,资源释放。有时候某些代码必须执行就可以写到finally里边。 注意:尽量不要再finally里边写return,永远返回finally里的结果。
try{
可能产生异常的代码
}catch(定义一个异常的变量,用来接收try中抛出来的异常对象){
异常的处理逻辑,异常之后怎么处理异常对象
一般会记录在日志中
}
finally{
必须要执行的代码,无论是否出现异常,都会执行。
}边栏推荐
- 1182:合影效果
- Rich text - Test Case
- SQL injection file read / write
- Which securities company is better and safer to choose when opening an account for the inter-bank certificate of deposit fund with mobile phone
- Apache Doris becomes the top project of Apache
- Calculation of stock purchase and sale expenses
- Music website design based on harmonyos (portal page)
- Learn how Alibaba manages the data indicator system
- 线程的生命周期
- Implementation of single sign on
猜你喜欢

Automatic conversion - interview questions

股票 停牌

English translation plug-in installation of idea

Basic knowledge of hard disk (head, track, sector, cylinder)

Write a simple timeline

Boundary value analysis method for learning basic content of software testing (2)

SQL 優化經曆:從 30248秒到 0.001秒的經曆

Using transform:scale causes the page mouse hover event to disappear

104. maximum depth of binary tree

For the development of short video app, the elder warned me to choose the open source code
随机推荐
Rman Backup Report Ora - 19809 Ora - 19804
Scenario method and error recommendation method for learning basic content of software testing (2)
什么是在线开户?现在网上开户安全么?
剑指Offer | 斐波那契数列
分而治之之经典Hanoi
构造方法绝不是在new()之后就立马执行!!!!!
数据挖掘建模实战
Stock suspension
Differences between task parameter types inout and ref
買賣股票費用計算
自动转换之-面试题
Edit the live broadcast source code with me. How to write the live broadcast app code
RMAN backup message ora-19809 ora-19804
买卖股票费用计算
Learn how Alibaba manages the data indicator system
Assertions used in the interface automation platform
Is it safe for Huatai Securities to open an account online? What is the handling process
P2394 yyy loves Chemistry I
Prototype chain JS
Is it safe to open an account for mobile phone stock speculation?