当前位置:网站首页>Scala higher order (10): exception handling in Scala
Scala higher order (10): exception handling in Scala
2022-07-29 07:22:00 【Think hard, Xiao Zhao】
Hello everyone , I can't think of Xiao Zhao .
Creation time :2022 year 7 month 27 Japan
Blog home page : Click here to enter the blog home page
—— Migrant workers in the new era
—— Look at the world with another kind of thinking logic
Today is to join CSDN Of the 1243 God . I think it's helpful and troublesome. I like it 、 Comment on 、️ Collection
List of articles
Scala Exception mechanism in syntax processing and Java similar , But it's different .
One 、 Exception Overview
- Exception mechanism : Abnormal conditions occurred during the execution of the program .
Code demonstration :
public class ExceptionText {
public static void main(String[] args) {
int a=100;
int b=0;
System.out.println(a/b);
}
}
Running results :

Two 、 review Java Abnormal mechanism in
Java There are two ways of exception handling in
- At the location of the method declaration , Use throws keyword , Throw it to the next level . Who calls me , I'll throw it to whoever . Throw it to the next level .
public class ExceptionText {
public static void main(String[] args) throws Exception{
int a=100;
int b=0;
divide(a,b);
}
public static void divide(int a, int b) throws Exception{
int c = a / b;
System.out.println(c);
}
}
- Use try…catch Statement to catch exceptions .
public class ExceptionText {
public static void main(String[] args){
int a=100;
int b=0;
try {
divide(a,b);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void divide(int a, int b) throws Exception{
int c = a / b;
System.out.println(c);
}
Be careful :
1.Java If you keep throwing up after the exception in , Finally, it was thrown to main Method ,main Methods keep throwing up , Thrown to the caller JVM,JVM Know that this exception happened , There is only one result . End java Execution of procedures .
2.try An exception occurs in a line in the statement, and the subsequent code of that line will not be executed try…catch After the capture , Subsequent code can be executed .
try…catch and finally summary
- Grammar format :
try {
}catch(OneException e) {
}catch(TwoException e) {
}finally {
}
try Contains code that may cause exceptions
try And then catch,catch There can be one or more ,catch Is the exception that needs to be caught
finally Express : Whether it's an exception , There are still no exceptions ,finally The code in the is executed ,finally and catch
Can be used separately , but finally It has to be with try Use it together
try {
}finally {
}
catch( abnormal 1 | abnormal 2 | abnormal 3 |......)jdk8 New characteristics !!
Sample code (1):
public class ExceptionText {
public static void main(String[] args){
int a=100;
int b=0;
try {
divide(a,b);
// There is an exception in the previous line of code , Go straight into catch Inside !!
System.out.println(" Can I execute ?");
} catch (Exception e) {
System.out.println(" By 0 except !!");
}
}
public static void divide(int a, int b) throws Exception{
int c = a / b;
System.out.println(c);
}
}
Running results :
By 0 except !!
Sample code (2):
public class ExceptionText {
public static void main(String[] args){
int a=100;
int b=0;
try {
divide(a,b);
// There is an exception in the previous line of code , Go straight into catch Inside !!
System.out.println(" Can I execute ?");
} catch (Exception e) {
System.out.println(" By 0 except !!");
}finally {
System.out.println("finally Yes !!");
}
}
public static void divide(int a, int b) throws Exception{
int c = a / b;
System.out.println(c);
}
}
Running results :
By 0 except !!
finally Yes !!
throws And try…catch How to choose ?
Abnormal use needs to be reported throws, Use... When you need to catch exceptions try…catch Capture !!
finally Important interview questions
Sample code (3):
public class FinallyText {
public static void main(String[] args) {
System.out.println(n());
}
public static int n(){
int i=100;
try {
return i;
}finally {
i++;
}
}
}
3、 ... and 、Scala Abnormal mechanism in
- The code that will cause exceptions is encapsulated in
tryIn block . staytryBlock followed by acatchHandler to catch exceptions . If anything goes wrong ,catchThe handler will process it , The program will not terminate abnormally . - Scala The abnormal working mechanism and Java equally , however Scala No, “
checked( Compile time )” abnormal , namely Scala There is no concept of compiling exceptions , Exceptions are caught and handled at runtime . - The mechanism of exception catching is the same as in other languages , If something goes wrong ,catch Clauses are captured in order . therefore , stay catch clause , The more specific the exception, the more it depends on the front , The more common the anomaly, the later , If the more common exceptions are written before , Write the specific exception after , stay Scala There's no mistake in reporting , But this is a very bad programming style .
finallyClause is used to perform the steps that need to be performed whether normal processing or exception occurs , Generally used for object cleaning , This and Java equally .- use
throwkeyword , Throw an exception object . All exceptions areThrowableSubtypes of .throwExpressions are of type , NamelyNothing, becauseNothingIs a subtype of all types , thereforethrowExpressions can be used where types are needed . - java Provides
throwsKeyword to declare an exception . You can use method definitions to declare exceptions . It provides the caller function with information that this method might throw this exception . It helps to call function handling and include the code intry-catchIn block , To avoid abnormal program termination . stay Scala in , have access to throws Annotations to declare exceptions .
def main(args: Array[String]): Unit = {
f11()
}
@throws(classOf[NumberFormatException])
def f11()={
"abc".toInt
}
Sample code (4):
object Test_Exception {
def main(args: Array[String]): Unit = {
try{
val n =10 /0;
}catch {
case e: ArithmeticException =>{
println(" Arithmetic exception occurred ")
}
case e: Exception => {
println(" A general exception occurred ")
}
}finally {
println(" End of processing ")
}
}
}
This time Scala The content shared by the exception mechanism in ends here , And Java Compared with the exception mechanism, there are indeed many flexible places , I hope that's helpful !!!
边栏推荐
- Homebrew brew update doesn't respond for a long time (or stuck in updating homebrew...)
- Paper reading (62):pointer networks
- Fillder use
- 如何使用gs_expansion扩展节点
- 微服务远程调用
- My personal website doesn't allow access to wechat, so I did this
- Custom events
- OCR光学字符识别方法汇总
- It's enough for MySQL to have this article (disgusting and crazy typing 37k words, just for Bo Jun's praise!!!)
- 计算程序运行时间 demo
猜你喜欢

js第四天流程控制(if语句和switch语句)

JS chicken laying eggs and egg laying chickens. Who appeared earlier, object or function? Is function an instance of function?

Redis基础篇

Interface test actual project 03: execute test cases

1-后台项目搭建

Vscode remote debugging PHP solution through remotessh and Xdebug

接口测试实战项目03:执行测试用例

以太网接口介绍

Use vscode to configure Mysql to realize connection, query, and other functions

Kubernetes (五) ---------部署 Kubernetes Dashboard
随机推荐
Scala 高阶(九):Scala中的模式匹配
Thoroughly understand kubernetes scheduling framework and plug-ins
js第四天流程控制(if语句和switch语句)
ETL为什么经常变成ELT甚至LET?
Summary of OCR optical character recognition methods
Full process flow of CMOS chip manufacturing
tp6 使用 ProtoBuf
After 4 years of development and 13K, if you want to change to automated testing, can your salary still rise···
When NPM is installed, it is stuck. There are five solutions
Problems encountered in vmware16 installing virtual machines
对Vintage分析的一些学习理解
SQL优化
以太网接口介绍
[solution] error: lib/bridge_ generated. dart:837:9: Error: The parameter ‘ptr‘ of the method ‘FlutterRustB
Operator3 - design an operator
我的个人网站不让接入微信登录,于是我做了这个
BeanUtils.setProperty()
Implementation of book borrowing management system based on C language
Other basic monitoring items of ZABBIX
WPF nested layout case