First, air safety

1.1 a null pointer

In Java, you can define a variable with no default assignment, because the Java system assigns us a default value by default, and Java can define a variable with a null assignment, so that all use of the variable will show whether the variable is null or not. As a result, nullPointerExceptions occur frequently, causing us a lot of trouble.

Kotlin’s type system is designed to eliminate NullPointerExceptions from our code.

The only possible cause of NPE may be:

  • Explicitly call throw NullPointerException()
  • Use what is described below!! The operator
  • External Java code
  • There are some data inconsistencies for initializations (such as an uninitialized this used somewhere in the constructor)

Variables cannot be null unless otherwise specified, so that the runtime crash is resolved at its root. Variable “name” must be initialized:

1.2 Cavitation (?)

Kotlin distinguishes between nullable and non-nullable types, so the compiler is always alert to the potential danger that you want a nullable variable to run and it may not exist. To address this risk, Kotlin does not allow you to call functions on nullable values unless you take over security management. The diagram below:

So how does perfection make a variable nullable?

The format for defining a variable of nullable type is: modifier Variable name: type? = value

Fun main() {// nullability // data type followed by "?" Can be the data type or null var age :Int? = 15 age = nullCopy the code

1.3 Safe Call operators (? .).

  • Nullable type variable? .properties/functions. Returns NULL if the nullable type variable is null
  • NullPointException is effectively avoided because if one of the links is null, the entire expression is null

The safe call operator must be used when calling a function using an available type. .). Otherwise, the compilation fails.

// The safe call operator println(age? .plus(20))//nullCopy the code

Nullable types are used in functions

When a function returns a value, the code in the function uses? To return a value, the type of the return value of the function must be followed by? Symbols.

Fun userInfo() : Int? {//name is a nullable String attribute. Var name:String? ="Java" name=null // use the security call operator (? .). return name? .length }Copy the code

1.4 Let operator

Let: variable? . Let {… }

What does the let operator do? Null is ignored during validation

Safe calls allow functions to be called on nullable types, but what if you want to do something extra, like create a new value, or call another function if it’s not null? You can use the security call operator with the let function. You can call the let function on any type, and its main purpose is to let you define one or more variables in 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)Copy the code

1.5 Using the non-null assertion operator (!! .).

!!!!! . Also known as the exclamation point operator, throws a NullPointerException when the variable value is null.

// Non-null assertion operator type = null println(type!! .toString())Copy the code

1.6 Using the null merge operator (? 🙂

? The: operator means that if the left-hand evaluation is null, the right-hand value is used.

type = null // println(type!! . The toString ()) / / null pointer exception println (" -- -- -- -- -- -- -- -- -- -- -- -- ") / / empty merge operator (? :) // if type is empty, run "Kotlin" println(type? : "Kotlin") type = "Java" // If type is "Java", run println(type? : "Kotlin")Copy the code

Use? : + let the if/else instead

println("---? :+let----") type = "" type = type? .let { "Kotlin" }? :"Java" println(type) type = null type = type? .let { "Kotlin" }? :"Java" println(type)Copy the code

1.7 Using the Type Conversion Operator (AS)

1.7.1 Unsafe conversion operator: AS

Sometimes a variable cannot be converted and an exception thrown, which is called an unsafe conversion. Unsafe casts are performed by infix operators.

Nullable String (String?) Cannot be cast to a non-null Int, which throws an exception.

var asTest :String? Println (asTest as Int);Copy the code

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)
Copy the code

1.7.8 Secure Conversion Operator: As?

as? Safely convert to a type. If the conversion is not possible, null is returned instead of throwing a ClassCastException.

Let’s modify it based on the above example.

var asTest :String? Println (asTest as Int)//ClassCastException (as? println(asTest as? Int)//nullCopy the code

Second, the abnormal

2.1 concept

An exception is a run-time problem that occurs in a program, causing it to terminate. This can happen due to running out of memory, arrays out of bounds, and conditions divided by zero. To handle this type of problem during program execution, use exception handling techniques. Exception handling is a technique for dealing with run-time problems and maintaining the flow of program execution. In Kotlin, all exception classes are subclasses of the 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 can 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: The finally block always performs whether to handle exceptions. So it’s 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.

An unchecked exception

An unchecked exception is an exception thrown because of an error in your 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 dividing a number by zero.
  • ArrayIndexOutOfBoundExceptions: don’t try to use the correct value index access thrown when an array.
  • 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 the try… Catch block

Try-catch blocks are used for exception handling in code. The try block contains code that might throw an exception, and the catch block is used to handle exceptions and must be written to the method. A try block must follow a catch block or a finally block or both.

2.2.1 Use the try syntax of catch blocks

fun main() { var name: String? = null try { name!! .plus("is good")// Error: NullPointerException} catch (e: NullPointerException) {println(e.message)}}Copy the code

2.2.2 Use the try syntax of the finally block

var name: String? = null try { name!! .plus("is good")// error: NullPointerException} finally {println(" all finished ")}Copy the code

2.2.3 Try catch syntax and finally block

var name: String? = null try { name!! .plus("is good")// Error: NullPointerException} catch (e: NullPointerException) {println(e.message)} finally {println(" all finished ")}Copy the code

2.3 finally block

Finally is a block that always executes whether or not an exception is handled. So it’s used to execute important code statements. As follows:

As in the code above, an exception has been raised, but the code in the finally block still executes.

Note: If the program exits (by calling exitProcess(Int) or any error that causes the process to abort), the finally block is not executed.

2.4 Throw keyword

The throw keyword is used to throw an explicit exception. It is used to throw custom exceptions. To throw an exception object, throw-expression is used.

Fun main() {try {// checkData(name) name!! .plus("is good")// Error: NullPointerException} catch (e: Exception) {println(e.message)}} // {// When STR is empty, ScException() STR? The first step: throw ScException ()} / / : custom exception class ScException () : IllegalArgumentException (" handsome abnormal time card ")Copy the code

2.5 Prerequisites

Kotlin provides built-in functions for traversal that you can use to customize exceptions to the message. These functions are prerequisites. You can use this function to customize the prerequisites so that the code is executed when the conditions are met.

function describe
checkNotNull If the argument is null, IllegalArgumentException is thrown; otherwise, a non-null value is returned
require If the argument is false, IllegalArgumentException is thrown
requireNotNull If the argument is null, IllegalArgumentException is thrown; otherwise, a non-null value is returned
error If the argument is null, IllegalArgumentException is thrown with an error message, otherwise a non-null value is returned
assert If the argument is false, an AssertError exception is thrown with the assertion compiler flag
CheckData (name) name!! .plus("is good")// Error: NullPointerException} catch (e: Exception) {println(e.message)}} // {// When STR is empty, execute the lambda expression checkNotNull(STR,{" checkNotNull prerequisite exception "})}Copy the code