Exceptions


what is exception in kotlin ?

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.

An exception can occur for many different reasons, below given are some scenarios where exception occurs.

  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

KProperty in kotlin

Error in kotlin

Error is caused by the environment in which the application is hosted/deployed, and you cannot handle errors

You can't handle a Error in catch block because your application won't recover by doing that.

Best Examples for Error are OutOfMemoryError when JVM runs out of memory, StackOverflowError when stack overflow,VirtualMachineError JVM is broken or has run out of resources.

Best way to handle the Error is prevent the situations which causes the error, if an error arises then you cannot control/handle it.

File Operations in kotlin

Types of Exceptions

There are mainly two types of exception and error is considered as exception but i am not gonna include error as part of exceptions.

  • Checked Exception
  • Un-Checked Exception

Checked Exception :

  • Compiler is able to recognize them at compile time and user should solve before executing the code
  • Methods that throw checked exceptions must indicate so with throws which must propagate up the calling stack until the exception is handled
  • Checked exceptions require explicit catching with a catch block if you are not delegating the exception
  • Examples for checked exceptions are :
    • EOFException
    • Exception
There is no checked exception in kotlin, so every exception or error belongs to un-checked exceptions. We neither handle the exceptions with try .. catch not delegate the exception using throws keyword.

Un-Checked Exception :

  • Compiler will not able to judge that is is an exception during the compile time
  • Happens only at runtime (i.e. out-of-bounds, divide by zero, etc.) mostly because of logical error
  • Methods may throw unchecked exceptions but do not have to indicate so in declaration using throws keysword

Read Properties File in Kotlin

Catching Exceptions in Kotlin

Exception cause crash of program, if an exception caught during the runtime we might want to perform some operation.

We can catch the exceptions using the try..catch, code which throws exception is placed in try block and the operation we want to perform if exception is thrown is placed in catch block.

The code within the try block is referred as protected code. try-catch-kotlin

try block in kotlin :

try block is nothing but a block which contains a certain code and that certain code may or may not behave abnormally, when the code behaves abnormally the program throws an exception but when it behaves normally it will not throw any exception.

In layman terms, try block is nothing but a room in hospital which is little sensitive and we are having patient inside the particular room, when something unexpected happens in that room the hospital will be ready to handle the situation.

catch block in kotlin :

The catch block is nothing but a block of code, so whenever something abnormal happens in the try block the associated catch block will be executed, the catch block will be having code which will efficiently handle that particular exceptional situation

In catch block, user should mention what is the exception that we should handle because we cannot handle all the exceptions as different exceptions will require a different code to handle the situation.

Catch block with exception fun main(args:Array<String>) { try { println("below code throws exception") var c = 5/0 println("I am after the exception") } catch (e: Exception ) { println("catch block code") } } catch block without exception fun main(args:Array<String>) { try { println("try block code") } catch (e: Exception ) { println("catch block code") } }

Try..Catch as Expression in kotlin :

Using try..catch block we can assign value in kotlin, so we can use try..catch as expression. As you are aware the last statement will be considered as return value in try or in catch. fun main(args:Array<String>) { var tryCatchRetrunValue = try { println("try block code") 7/0 } catch (e: Exception ) { 0 } println(the denominator value is : $tryCatchRetrunValue) }

finally block in kotlin :

Finally block is also a normal block which contains code but finally block will be executed irrespective of whether an exception occurred or not in try block

try-catch-finally-kotlin Finally block code with exception fun main(args:Array<String>) { try { println("below code throws exception") var c = 5/0 println("I am after the exception") } catch(e:Exception){ println("received an exception") } finally { println("finally block code") } } Finally block without exception fun main(args:Array<String>) { try { println("try block code") } catch(e:Exception){ println("received an exception") } finally { println("finally block code") } } Finally block without catch block fun main(args:Array<String>) { try { println("try block code") } finally { println("finally block code") } } Basic rules of finally :

  • finally block will be used to perform code clean up activities like : disconnecting browser, closing all files, closing the browser.
  • try block is must to write finally block
  • Only one finally block is allowed with try block
  • Only one finally block is allowed with try block
When finally block will not execute :

  • When System.exit() code occurs in try or in catch block
  • When JVM crashes
  • When try block is executed infinitely without breaking
  • When user stopped the execution (just for fun).
Basic rules of try..catch..finally :

Sealed Classes in kotlin

throw keyword in Exceptions

So far we are trying to catch and handle the exceptions. Before you can catch an exception, some code somewhere must throw one

Any code can throw an exception exception: your code, code from a package written by someone else such as the packages that come with the Java platform selenium webdriver, or the Java runtime environment.

Regardless of what/who throws the exception, it's always thrown using throw statement.

Below program throws ArithmeticException with some reason, we can throw any exception using throw keyword.
fun main(args: Array<String>) { validateAge(13) println("code after validation check...") } fun validateAge(age: Int) { if (age < 18) throw ArithmeticException("under 18, you cannot vote") else println("eligible for voting") }

Output :
throw-exception-kotlin

Throw keyword as expression in kotlin :

When a code/construct returns a value then it is called as expression, if it does not return any value then we call it as statement.

We can use the throw keyword for assignment, like we can assign value if condition passes otherwise we can throw exception like below. fun main(args: Array<String>) { validateAge(35) println("code after validation check...") } fun validateAge(age: Int) { var exceptionVariable = if (age < 18) ArithmeticException("under 18, you cannot vote") //return value, raises exception else "voted"// return value println(exceptionVariable) }

Throw keyword with Elvis Operator

Elvis operator is perform on nullable object to check whether give value is null or not, if it is null then Elvis operator will replace the value with given default value.

We will be replace the default value with throw Exception, In below program if name is null then program will raise exception. fun main(args: Array<String>) { var name = null val someValue = name ?: throw Exception("Throwing exception from Elvis operator") println("code after validation check...") } throw-keyword-elvis-operator-kotlin

Any & Unit & Nothing

throws annotation in Exceptions

@Throws annotation used in the functions signature , to delegate the exception to the caller.

We can handle the exception using try..catch but sometimes there will be scenario where you should not handle the exception, In such cases we must delegate the exception using throws annotation

For example, you are trying to read a file based on the path passed by the user, there is chance that the file may or may not present in the local system.

In this case, you should not handle the exception as you don't know what the file contains in it.

So we must inform the user by delegating the exception, and it is up to end customer to handle exception or to stop the program.

In below example, we are raising ArithmeticException in the program fun main(args: Array<String>) { validateAge(15) println("code after validation check...") } @Throws(ArithmeticException::class) fun validateAge(age: Int){ if (age < 18) throw ArithmeticException("under 18, you cannot vote") else println("eligible for voting") }


Note : We should not try to delegate the exception all the times, sometimes we should handle the exception. We should handle the exception when we have better solution to overcome the exception.

As per me, all the Checked Exceptions must be delegated to the caller function.

Elvis Operator [?:]

Difference between throw and throws keywords

The throw keyword handover user created exception to JVM manually, throws keyword is used to delegate the responsibility of exception handling to the caller of the method

The throw keyword is followed by exception object, throws keyword is followed by the list of the exception class which can occur in the method

The throw keyword can throw only one exception object, the throws keyword can declare multiple exception classes separated by a comma or can have top most exception to delegate all the subclass exceptions.

throw keyword is used in function implementation but throws is used in function signature.

Checked exception cannot be propagated using throw only but Checked exception can be propagated with throws.

Please refer the syntaxes in above topic.

Loops in Kotlin

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech