Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Throw Custom Exception

How can I throw a custom exception in Kotlin? I didn't really get that much off the docs...

In the docs, it gets described what each exception needs, but how exactly do I implement it?

like image 369
OhMad Avatar asked Jul 18 '17 09:07

OhMad


People also ask

How do you throw a custom exception in Kotlin?

Example 1 – Create Custom Exception in Kotlin In this Example, we shall create a custom exception named InvalidNameException, which we shall throw when name of a person is invalid. fun main(args: Array<String>) { var name = "Tutorial 60" try { validateName(name) } catch (e : InvalidNameException){ println(e.

How do you throw multiple exceptions in Kotlin?

Kotlin does not support throwing multiple exceptions at the same time, however we can implement this functionality using some other functions provided by the Kotlin library.

How does Kotlin handle runtime exception?

In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods.


2 Answers

One thing to keep in mind: if you are using the IntelliJ IDE, just a simple copy/paste of Java code can convert it to Kotlin.

Coming to your question, now. If you want to create a custom Exception, just extend Exception class like:

class TestException(message:String): Exception(message) 

and throw it like:

throw TestException("Hey, I am testing it") 
like image 68
chandil03 Avatar answered Oct 03 '22 05:10

chandil03


Most of these answers just ignore the fact that Exception has 4 constructors. If you want to be able to use it in all cases where a normal exception works do:

class CustomException : Exception {     constructor() : super()     constructor(message: String) : super(message)     constructor(message: String, cause: Throwable) : super(message, cause)     constructor(cause: Throwable) : super(cause) } 

this overwrites all 4 constructors and just passes the arguments along.

EDIT: Please scroll down to R. Agnese answer, it manages to do this without overriding 4 constructors which is error prone.

like image 40
DownloadPizza Avatar answered Oct 03 '22 05:10

DownloadPizza