Reputation: 11323
This is sort of a fun question, but what is the shortest possible Exception producing code in Kotlin? Any Exception.
Something like:
throw null!!
which will throw an NPE.
...but hey that is still quite a long line with 12 chars. It is actually quite usefull for testing things like logging of Exceptions in analytics and such.
Upvotes: 0
Views: 125
Reputation: 6992
In terms of the number of character, you can easily declare a property which has a getter function throwing Exception
:
val T: Nothing
get() = throw Exception("For testing purpose!!")
Reminder: The usages of this code should probably be removed immediately after use, because it carries no meaning.
If you simply want to type less characters, I suggest to create a Live Template for that.
Upvotes: 1
Reputation: 8371
If you don't mind putting some utility code somewhere you can use this code:
e()
And the utility code:
fun e() : Nothing = throw Exception()
The Nothing
return type tells the compiler that the function will never return.
Upvotes: 0
Reputation: 147951
Here's an even shorter one:
1/0
It throws java.lang.ArithmeticException: / by zero
.
Upvotes: 6
Reputation: 11323
So far the shortest I can imagine is:
""[1]
5 chars and will lead to StringIndexOutOfBoundsException: length=0; index=1
Upvotes: 0