Kotlin series exceptions and Kotlin Series Issues

Source: Internet
Author: User
Tags finally block

Kotlin series exceptions and Kotlin Series Issues

In this section, we will talk about exceptions in Kotlin.

Java exceptions

We know that exceptions in Java are an endless topic. When talking about exceptions, the first thing that comes to mind isTry... catch... finally is the same in Kotlin. The usage is almost unchanged, but there are also some small changes. Here we still use the previous practice: first put the Java code and then go to the Kotlin code.

Java code

public int readNumber(BufferedReader reader) throws IOException {    int result = 0;    String line = reader.readLine();    result = Integer.parseInt(line);    reader.close();    return result;}

The above codeThe readLine () method throwsIOException, which is a checked exception, must be explicitly processed, either thrown on the method declaration or captured internally for processing. In fact,The parseInt () method also throws a runtime exception. Java does not require us to capture and handle runtime exceptions, but here we will explain it in concert with the following content, handle this exception.
The modified code is like this.

Java code

public int readNumber(BufferedReader reader) throws IOException { int result = 0; String line = reader.readLine(); try { result = Integer.parseInt(line); }catch (NumberFormatException e){ e.printStackTrace(); result = -1; }finally { if (reader != null){ reader.close(); } } return result;}

Used hereTry... catch... finally to improve the code. In Java, a function can end normally or throw an exception when an error occurs. The method caller can capture this exception and handle it. If it is not processed, an exception will be thrown again along the call stack.

Throw in Kotlin as an expression

In Kotlin, the exception handling mechanism is similar, but unlike in JavaThrow is an expression that can be used as part of another expression. Let's take a look at the following code.

Kotlin code

fun test(){ val n = 1; val res = if (n in 0..100){ n }else{ throw IllegalArgumentException("error") } println(res)}

Here, the previous content has also been mentioned.If is also an expression. In the code above, if the value of n is 0-, the res value is initialized to the value of n. if not, an exception is thrown and the res value is not initialized. Like our previous code, unlike Java, the exception thrown does not need to be used.new。

Exception in Kotlin

At the beginning, we provided a JavaTry... catch... finally example. Here we use the Kotlin code to compare the differences between the two.

Kotlin code

fun readNumber(reader: BufferedReader): Int{ var result = 0 val line = reader.readLine() try { result = Integer.parseInt(line) } catch (e: NumberFormatException) { e.printStackTrace() result = -1 } finally { reader.close() } return result}

The above Code requires attention.
1. As mentioned earlier, the type of the function return value is written at the end: Split.
2. You will find that Kotlin does not need to explicitly declare the thrownIOException.
3. Variable Declaration is alsoVariable name: Format of the variable type.

In Kotlin, there is no distinction between checked exceptions and non-checked exceptions. The reason is that, for example, if an error occurs when we close the file, we can't do anything except this exception. Kotlin directly removes this code.
Some may have questions about the java codeFinally block contains such empty code

if (reader != null){ reader.close();}

Why does it disappear in Kotlin? This is because when the function parameter type is declared in KotlinReader: BufferedReader, indicating that this is a non-null value. If you want to declare it as a null value, you can write it like this.Reader: BufferedReader ?, In this case, it is required to be empty before close.

Try in Kotlin as expression

As we mentioned earlierThrow is used as an expression. In fact, try is also an expression.The try value is assigned to a variable. Let's continue with the above Code.

Kotlin code

fun readNumber(reader: BufferedReader): Int?{ var result = 0 val line = reader.readLine() result = try { Integer.parseInt(line) } catch (e: NumberFormatException) { e.printStackTrace() -1 } finally { reader.close() } return result}

You will find that the Code has become fewer. here we need to add a rule to understand the above Code.
WhenWhen try is used as an expression, if the try block runs normally, the last expression in the try block is the result. If an exception is thrownThe value of the last expression in the catch block is the result.
I understand if this rule is the code above.

Conclusion

The exception mechanism is designed to allow me to write more robust code. In Kotlin, we have made some improvements and improvements to Java's exception handling mechanism, allowing us to handle exceptions in a more concise way.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.