catalogue
1.5 use non null assertion operator (!!!.)
1.6 use the empty merge operator (?:)
1.7 using the type conversion operator (as)
1.7. 1 unsafe conversion operator: as
1.7. 8. Safe conversion operator: as?
2.2. 1 use the try syntax of the catch block
2.2. 2 use try syntax of finally block
2.2. 3. Try catch syntax and finally block
1, Air safety
1.1 null pointer
In Java, we can define a variable without assignment by default, because the Java system will assign us a default value by default, and Java can define a variable with null assignment, so that when using this variable, it will be displayed to judge whether the variable is null. This makes the null pointer exception NullPointerException, which is common in Java, and brings us a lot of trouble.
Kotlin's type system is designed to eliminate NullPointerException from our code.
The only possible causes of NPE may be:
-
Explicitly call throw NullPointerException()
-
The following description is used!! Operator
-
Caused by external Java code
-
For initialization, there are some data inconsistencies (for example, an uninitialized this is used somewhere in the constructor)
Unless otherwise specified, variables cannot be null values, so that the runtime crash is resolved at its root. As shown in the following figure, an error is reported: the variable "name" must be initialized:
1.2 nullability (?)
Kotlin distinguishes nullable types from non nullable types. Therefore, you need to run a nullable type variable, which may not exist. The compiler is always vigilant against this potential danger. In order to deal with this risk, kotlin does not allow you to call functions on nullable type values unless you actively take over security management. As shown below:
So perfect how to make variables nullable.
The format of defining a variable of nullable type is: modifier variable name: type= value
fun main() { //Nullability //Add "?" after the data type, Indicates that it can be the data type or null var age :Int? = 15 age = null//No error reported }
1.3 safe call operator (?.)
-
Nullable type variable Properties / functions. Returns NULL if the nullable type variable is null
-
It can effectively avoid null reference exception (NullPointException), because as long as one of the chain is null, the whole expression is null
When a function is called with an available type, the safe call operator (?.) must be used, Otherwise, the compilation will not pass.
//Safe call operator println(age?.plus(20))//null
Nullable type used in function
When a function has a return value, if the code in the function uses To return a value, the type of the return value of the function should also be followed by? Symbol.
//The return value Int can be null fun userInfo() : Int? { //name = is a nullable String type attribute var name:String?="Java" name=null //Use the safe call operator (?.) return name?.length }
1.4 let operator
Let usage: variable let{ … }
The function of let operator: use the symbol null is ignored during validation
Safe calling allows functions to be called on nullable types, but what if you want to do something extra, such as creating a new value or calling other functions when it is judged not to be null? You can use the safe call operator with the let function. You can call the let function in any type. Its main function is to let you define one or more variables within the specified scope.
//let var type: String? = "java" type = type?.let { if (it.isNotBlank()) { "$it,Non blank string" }else{ "Kotlin" } } println(type) type = ""//Null character type = type?.let { if (it.isNotBlank()) { "$it,Non blank string" }else{ "Kotlin" } } println(type)
1.5 use non null assertion operator (!!!.)
!!. It is also called exclamation point operator. When the variable value is null, it will throw NullPointerException.
//Non null assertion operator type = null println(type!!.toString())
1.6 use the empty merge operator (?:)
?: The operator means that if the evaluation result on the left is null, the result value on the right is used.
type = null //println(type!!.toString()) / / null pointer exception println("------------") //Empty merge operator (?) //When type is empty, run and print "Kotlin" println(type ?: "Kotlin") type = "Java" //When type ¢ is "Java", run and print "Java" println(type ?: "Kotlin")
Use?:+ let instead of if/else
println("---?:+let----") type = "" type = type?.let { "Kotlin" }?:"Java" println(type) type = null type = type?.let { "Kotlin" }?:"Java" println(type)
1.7 using the type conversion operator (as)
1.7. 1 unsafe conversion operator: as
Sometimes variables cannot be converted and exceptions are thrown, which is called unsafe conversion. Unsafe cast is performed by infix operator.
Can be an empty String (String?) Cannot convert to non null Int type, which will throw an exception.
var asTest :String? = "" //Unsafe conversion operator println(asTest as Int)
Exception in thread "main" java.lang.ClassCastException:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') at com.scc.kotlin.primary.NullKt.main(Null.kt:64) at com.scc.kotlin.primary.NullKt.main(Null.kt)
1.7. 8. Safe conversion operator: as?
as? Safely convert to a type. If the conversion cannot be performed, null is returned instead of throwing a ClassCastException exception.
Let's modify it based on the above example.
var asTest :String? = "" //Unsafe conversion operator as // println(asTest as Int)//ClassCastException //Safe conversion operator as? println(asTest as? Int)//null
2, Abnormal
2.1 concept
An exception is a runtime problem in a program that causes the program to terminate. This may occur due to insufficient memory space, array out of bounds, and conditional division by zero. To handle this type of problem during program execution, you can use exception handling techniques. Exception handling is a technology to deal with runtime problems and maintain program execution flow. In Kotlin, all exception classes are subclasses of Throwable class. To throw an exception object, Kotlin uses a throw expression.
Four different keywords are used in exception handling. They are:
-
Try: the try block contains a set of statements that may generate exceptions. Must be followed by catch or finally or both.
-
Catch: the catch block is used to catch exceptions thrown by the try block.
-
Finally: finally blocks always execute whether to handle exceptions. So it is used to execute important code statements.
-
Throw: the throw keyword is used to explicitly throw an exception.
Kotlin's exception handling is similar to Java.
Unchecked exception
An unchecked exception is an exception thrown due to an error in the code. This exception type extends the RuntimeException class. Check for unchecked exceptions at run time. Here are some examples of unchecked exceptions:
-
ArithmeticException: thrown when a number is divided by zero.
-
Arrayindexoutofboundexception: thrown when trying to access an array with an incorrect index value.
-
SecurityException: thrown by the security manager to indicate a security violation.
-
NullPointerException: thrown when a method or property is called on a null object.
Note: Kotlin does not support checked exceptions.
2.2 try...catch block
The try catch block is used for exception handling in the code. The try block contains code that may throw exceptions. The catch block is used to handle exceptions. This block must be written in the method. The try block must follow the catch block or finally block or both.
2.2. 1 use the try syntax of the catch block
fun main() { var name: String? = null try { name!!.plus("is good")//Error reported: NullPointerException } catch (e: NullPointerException) { println(e.message) } }
2.2. 2 use try syntax of finally block
var name: String? = null try { name!!.plus("is good")//Error reported: NullPointerException } finally { println("It's over") }
2.2. 3. Try catch syntax and finally block
var name: String? = null try { name!!.plus("is good")//Error reported: NullPointerException } catch (e: NullPointerException) { println(e.message) } finally { println("It's over") }
2.3 finally block
finally is a block that always executes whether or not an exception is handled. So it is used to execute important code statements. As follows:
As in the above code, an exception has been generated, but the code in the finally block has been executed.
Note: if the program exits (by calling exitProcess(Int) or any error that causes the process to abort), the finally block will not be executed.
2.4 throw keyword
Throw keyword is used to throw an explicit exception. It is used to throw custom exceptions. To throw an exception object, use throw expression.
fun main() { try { //Step 3: use checkData(name) name!!.plus("is good")//Error reported: NullPointerException } catch (e: Exception) { println(e.message) } } //Step 2: pass in nullable String fun checkData(str:String?){ //When str is empty, execute ScException() str?:throw ScException() } //Step 1: custom exception class ScException():IllegalArgumentException("Shuai second card abnormality")
2.5 prerequisites
Kotlin provides some built-in traversal functions, which can be used to customize the exceptions of information. These functions are prerequisite functions. You can use this function to customize the prerequisites, and the code will execute only when the conditions are met.
function | describe |
---|---|
checkNotNull | If the parameter is null, an IllegalArgumentException exception will be thrown; otherwise, a non null value will be returned |
require | If the parameter is false, an IllegalArgumentException is thrown |
requireNotNull | If the parameter is null, an IllegalArgumentException exception will be thrown; otherwise, a non null value will be returned |
error | If the parameter is null, an IllegalArgumentException exception is thrown and an error message is output. Otherwise, a non null value is returned |
assert | If the parameter is false, an AssertError exception is thrown and marked with the assertion compiler flag |
try { //Step 3: use checkData(name) name!!.plus("is good")//Error reported: NullPointerException } catch (e: Exception) { println(e.message) } } //Step 2: pass in nullable String fun checkData(str:String?){ //When str is empty, a lambda expression is executed checkNotNull(str,{"Shuai second card precondition exception"}) }