The documentation for Kotlin is now located on the new site. This page is kept for historical reasons

Skip to end of metadata
Go to start of metadata

The documentation for Kotlin is now located on the new site. This page is kept for historical reasons

Exceptions in Kotlin are not very different from any other language. the main difference from Java is that there're no checked exceptions in Kotlin, you can find out the motivation for this below.

Exception classes

All exception classes in Kotlin are descendants of the class Exception. Every exception has a message, stack trace and an optional cause.

To throw an exception object, one uses the throw expression:

throw MyException("Hi there!")

To catch an exception, one uses the try expression:

try { 
  // some code 
catch (e : SomeException) { 
  // handler 
finally { 
  // optional finally block 

As usual, there may be zero or more catch blocks, and finally may be omitted, but at least one catch or finally must be present.

Note that try is an expression, i.e. it may have a value:

val a : Int? = try { parseInt(input) } catch (e : NumberFormatException) { null }

The "returned" value of try expression with no finally is either the last expression in the try block or the last expression in the catch block (or blocks).

If finally block is present, its last expression is the value of try expression.

Why Kotlin has no checked exceptions

People with Java background may wonder why Kotlin does not have checked exceptions. There's so much said on this topic, that we just provide a few citations and one example here.

Our example is java.lang.Appendable – an interface from JDK, implemented by StringBuilder, that has, among others, the following method declaration:

Appendable append(CharSequence csq) throws IOException;

What does this signature say? It says that every time I append a string to something (a StringBuilder, some kind of a log, a console, etc) I have to catch those IOExceptions. Why? Because it might be performing IO (Writer also implements Appendable)... So it results into this kind of code all over the place:

try { 
catch (IOException e) { 
  // Must be safe 

And this is no good, see Effective Java Item 65: Don't ignore exceptions.

Some citations from prior art:

Bruce Eckel says in Does Java need Checked Exceptions? :

Examination of small programs leads to the conclusion that requiring exception specifications could both enhance developer productivity and enhance code quality, but experience with large software projects suggests a different result – decreased productivity and little or no increase in code quality.

Other citations of this sort:

  1. Java's checked exceptions were a mistake (Rod Waldhoff)
  2. The Trouble with Checked Exceptions (Anders Hejlsberg]

Java interoperability

Some details on Java interoperability are available here.

What's next

  • No labels


  1. Anonymous

    What's the plan for IDE support to help us not miss exceptions we really shouldn't have done? It annoys me no end when I write in an unchecked language, then a week later find it all breaks because there was an exception that I didn't catch because it never occured to me the function would throw it.

    1. We'll do our best to help you, with an IDE inspection, and, probably, some optional annotations.

    2. Anonymous

      Don't use exceptions for _expected_ faults - use nullables, ADTs (in Kotlin that would be "enum class", I think) etc. That way the consumer of your API is forced to pattern-match against the result value before getting to the meaningful result. Exceptions should be used in those cases where the handling is really not expected to happen until somewhere at the bottom of the call stack.

      1. Anonymous

        Using nullables means that if you forget to inspect the return value of a function for an error, that you will fail to handle it completely. This is fine in a functional language when calling something that has no side effects, but not necessarily otherwise.

        I have dealt with programs written this way and it was a major pain to debug. It also forces local handling of error conditions, which means that error condition handling code is scattered all over the place, with forwarding 'if' statements to pass it to higher levels, rather than being able to have all errors of a specific kind located in a single 'catch' clause several levels up. That clutters the code significantly and makes it hard to read.

        Also, nullables don't tell you what went wrong, only that "something" did, resulting in a null value. This makes debugging very painful, if null values can be returned for a variety of reasons and not just for a single one. (Case classes may help with this somewhat, at the cost of more syntax for handling.)

        In my experience, returning null and/or false instead of using exceptions to represent errors qualifies as an antipattern.

  2. Anonymous

    Aw, no pattern matching for "catch" blocks?

    1. For now, you can use when there, but we are considering some more special syntax

  3. Anonymous

    The reasoning used above to explain why checked exceptions are not part of Kotlin seems to be relying for its argument on several things that are not true.

    Firstly, contradicting what was stated in your example above, although StringBuilder does indeed extend Appendable, a catch block is not needed when appending to a StringBuilder. Appendable.append(String) does throw IOException, but StringBuilder.append(String) which overrides it does not. Therefore, If a user has a reference to a StringBuilder, then even in Java, no try..catch block will be necessary.

    A caller that has only a reference to an Appendable, however, with no knowledge of whether it is a StringBuilder or not, must assume that calling append might throw an IOException, and must be prepared to handle that exception in some way, because append actually CAN throw an IOException depending on what object is referenced by that Appendable reference. This is true regardless of whether or not IOException is a checked or an unchecked exception!

    Secondly, despite the reference to Effective Java above, the approach taken by Kotlin is exactly the OPPOSITE of what Joshua Bloch is suggesting in his book. Mr. Bloch is suggesting that non-fatal error conditions reported via exceptions should be HANDLED, rather than being silently ignored. The example given above suggests that not only should the IOException be ignored, but that the language should not even warn the user that this is the case. Doing this probably eliminates any possibility that either the compiler or the programmer might detect that an unhandled error condition could occur. The result is probably that everything seems fine during development, but sometime after release, the program eventually crashes unexpectedly when run by an end-user who happens to have a mostly-full hard disk. After all, the calling code had no idea that calling another method  (which internally did logging) could throw an IOException, so why would it have put in a catch clause to handle that failure case nicely?

    There is an implication in the example that the use of an empty try..catch block is somehow necessary or encouraged by the Java language. It really isn't. Empty catch clauses like these are just code written by an inexperienced programmer who doesn't know any better. (I blame Sun for their repeated failure to show users the right way to do this in their documentation and examples. Every time I see them put out example code containing empty catch clauses for brevity, I cringe.)

    There is a fairly standard way in Java to deal with many of these problems, which is used by a wide variety of libraries written by experts, but by not nearly enough ordinary programmers:


    Note that the Nested Exception approach isn't really addressed by any of the links that are referenced above. Rob Waldhoff's page comes the closest to describing it, but even he tries to have his ObjectPool example throw class Exception instead of throwing some kind of ObjectPoolException that would be specific to the class. Also, when he wraps exceptions, he wraps them in RuntimeExceptions (which is only really appropriate if you don't intend for the wrapped exceptions to be handled by the caller). I think it's relevant that all of the essays listed above were done before Java included explicit support for exception chaining (Throwable.getCause()) and as such the authors had no experience with using this feature to address the problems they were experiencing.

    I could see an argument for omitting checked exceptions from Kotlin if the compiler was capable of always detecting (at compile time!) that an unchecked exception would always be caught by a catch block upstream. This would be a really nice feature, and if I had this, I might not miss checked exceptions. Having the IDE detect this would be nice as well, but I think it's unreliable to make it anything but the compiler's ultimate responsibility, since an IDE user may not think to look for and fix all such problems. Using pattern matching on return values, as suggested by a previous poster, seems insufficient to me also since there is no guarantee that a caller will even inspect the return value of a function at all, and might therefore not notice an error condition reported as part of a return value.

    I don't mean to imply that the question of whether or not to have checked exceptions is a simple issue. It's not. However, I do think that the question needs to be dealt with using the best arguments available to both sides. It seems to me that from what I've seen above, that the "pro-checked-exceptions" side of the argument is not fully represented so far. Checked exceptions have important applications in provably ensuring that certain types of errors always get handled. In programming domains where failure is unacceptable (e.g. medical devices, Mars rovers, etc.), that extra layer of compile-time security can be a very. very important help towards making sure the program doesn't misbehave even when things go wrong. In particular, I think that a Java compiler warning the user about an unhandled non-fatal error condition in the specific scenario given above (by requiring the presence of the try..catch block for a possible non-fatal I/O error during logging) is a feature, not a bug. Eliminating the warning doesn't eliminate the problem that the warning is detecting... it just hides it.

    1. Anonymous

    2. Anonymous

    3. I should have used StringReader in the example, will fix it soon.

      1. How to design API in Kotlin where method call require to handle more than one result case:

        fun moveMoney(IdOfDebtAccount,IdOfCreditAccount, Amount)
          throws NotEnoughFundsOnDebtAccount,
          FundsTrasferLimitExceededForDebtAccount, //e.g. can't take more than $10 000 in a day

        It is expected by design that all listed exception cases will be handled explicityly, because all this situaltions will happen and application logic should handle them properly (e.g. display corresponding error screen to customer and/or suggest some possible future steps).

        For example, on ATM, with catch(FundsTrasferLimitExceededForDebtAccount) we could display current cash withdraw limits for customer (can't take yet $5 000 when $6 000 already taken this day, but $4 000 is still available).

        P.S. Probably StringReader won't be a good example because reading from closed stream is IOExceptin and sure it is possiple to close() StringReader and then try to read something from closed stream.

        1. The case you are making here is interesting. One solution would be to return a value of type Result which has subtypes for each case you are talking about and use pattern matching to be sure all the cases are covered (see Enum classes).

          The main difference with exceptions is that values are not propagated automatically up the stack, which may be inconvenient.

          1. In example above I'm following two goals:

            1. No one can simply ignore special result cases like NotEnoughFundsOnDebtAccount
            2. If I add yet more special cases then I won't be able to compile my code unless I add handling for new case in all method call ocurrences. Yes, I intentionaly want to break backward compatibility in this case because business rules changed in incompatible way and I must reflect this chanes in code.

            >One solution would be to return a value of type Result which has subtypes for each casefun moveMoney(IdOfDebtAccount,IdOfCreditAccount, Amount):MoveMoneyResultWhere:

            • MoveMoneyResultSuccess extends MoveMoneyResult
            • MoveMoneyResultNotEnoghtFunds extends MoveMoneyResult

            At first:

              anyone can call moveMoney(..) and ignore result at all, and this is worst case. All my code design affords just ruined here.

            At second:

              val result:MoveMoneyResult = moveMoney(...);

            Unknown macro: {    is MoveMoneyResultSuccess  -> System.out?.println("OK")    is MoveMoneyResultNotEnoghtFunds -> System.out?.println("Not enough funds on account")  }

            In this case if I add new result type, i.e. MoveMoneyResultFundsTrasferLimitExceededForDebtAccount, compiler will not force me to fix all moveMoney(...) result types.

            (Yes, I can use search and replace but there is no 100% guaranty that I will do search-n-replace, either I can skip some cases by accident)

            There will be a runtime exception if nothing is matched, but this will be same as if I throw Unckeched Exception.

    4. Anonymous

    5. The Appendable example demonstrates one of the major problems with checked exceptions.  If you are writing an interface how can you declare all the exception types it will throw without knowing about all possible implementations?

      Why must a caller of append() assume that it can throw an IOException?  That assumes the implementing class is performing IO and there is nothing in the Appendable interface that implies that is the case.  What if append() sends a JMS message?  Or writes to a database?  Should it throw SQLException and JMSException too?

      Runnable and Callable are good examples of this problem.  Runnable.run() doesn't declare any exceptions so implementations can only throw RuntimeExceptions which completely sidesteps the checked exception mechanism.  Callable.call() declares Exception.  All that tells you is that it might throw an exception.  How are you any better off than with unchecked exceptions?

      An application developer is in a better position to know what exceptions can be thrown by an interface method than the writer of the interface because the application developer knows what classes are deployed in his application.  Let's imagine append() in Kotlin without checked exceptions.  If the Appendable objects in an application will always be StringWriters or a class that writes text to the screen then exceptions could be safely ignored.  If the append() implementation performed IO then it would be wise to catch IOException.  And if the append() method throws an exception that the writer of Appendable had never heard of then the application developer could catch that.

  4. I think its a shame that the issue of checked exceptions is seen by developers as existing the way Java does it, or not at all.  Given that black & white choice, I applaud Kotlin and other post-Java languages for dismissing them.  However, Kotlin, being a new language and one that aims to be safer than Java should consider how to do it better than Java rather than not having them, as they do add some safety.  It's Java's specific implementation of them that makes them a pain, not the idea of them.

    I think one aspect of the pain is that Java makes an exception checked or not by its very type. I'd rather have this determination occur at a method's declaration.  One way to do this is to establish that any "throws" part of a method declaration in Kotlin means its checked.  If the intention is instead merely to document that the method might throw something without it being checked, then use javadocs.

    The other aspect of the pain of checked exceptions in Java is that reacting to them is painful. I usually end up wrapping the exception, which is a language-kludge.  I propose that if a caller wishes to essentially ignore the possibility of the exception, that there be some statement that declares this.  Perhaps some sort of annotation ignoring the exception, or maybe within the block of code that the throw could happen you put "throws InterruptedException" as a line.

    1. WHat you propose does not seem to help with the problem stated in the text: virtual functions.

      1. Andrey, I looked at the Classes and Inheritance page which describes virtual functions, and I don't see any mention of the word "exception". Same here – no reference to virtual functions. Can you elaborate on what you mean and how my proposal doesn't help?

        1. I meant the Appendable example mentioned above.

          1. Ok.  In my proposal I didn't consider how to bridge the Java - Kotlin divide.  

            If all Java's methods that throw checked exceptions become checked in Kotlin, a straight-forward reasonable approach, then my proposal does still help.  The caller of the append() method can add the "throws IOException" statement somewhere within the code block (NOT the method declaration), to essentially ignore the exception from a checked point of view.  This means this calling method need not re-declare the throws in the method. I think that's a big help since in Java, checked exceptions have a viral effect on the API and this provides a way to stop it.

            Another approach is for the language designers (you) to establish that there are certain Java exceptions, like IOException, or SQLException, etc. that if declared on a Java method that Kotlin calls, it will ignore it.  Perhaps any exception under the java.* or javax.* namespaces get this treatment but not others.

            And another approach is to consider all of Java's's methods to not throw any checked exceptions, as far as Java is concerned.


            Another idea occurred to me.  In my proposal I suggested the throws statement could be used in code blocks to ignore that checked exception.  If this declaration could also go at the top of the source file, after the import statements, then it would mean that it is in effect for all code blocks in the source file.  This might be done for exceptions like IOException, or SQLException.

    2. Anonymous

      I agree with you that many things about Java's implementation of checked exceptions are broken. For instance:

      1) There is no single base class for checked exceptions that distinguishes them from unchecked exceptions. It is therefore difficult for a catch clause to catch (and wrap) all checked exceptions while letting the unchecked ones propagate outwards.

      2) A similar problem exists for having a 'catch' clause that can catch any unchecked exception (but ONLY unchecked exceptions). This often results in duplicate catch clauses for RuntimeException and Error that do the same thing.

      3) Some common exceptions that should have been unchecked are in fact checked. java.lang.InterruptedException comes to mind.

      4) To do statically checked exceptions "right", the language really needs full Generics support. Unfortunately, Generics came to Java relatively late in its development, and many of the Java libraries were already written by then. This means that some of the best patterns for handling checked exception handling don't exist in a variety of common legacy classes or classes written in libraries. For instance, a typical Visitor interface is declared like this:

      instead of like this, which makes writing checked-exception-safe code MUCH easier, at least in cases where an upper bound (2 in this case) can be put on the number of types of checked exceptions that might possibly thrown:

      However, in the general case where an arbitrary number of checked exception types could be thrown, the language changes that will be added in Java 8 as part of closure support will be needed:


      which will allow:

      which can throw any number of exceptions:

      One place that I disagree with you, though, is your statement that "wrapping an exception is a language-kludge". Although I agree that the syntax for doing this could be nicer and more concise, I think that exception wrapping at a subsystem boundary is actually a very important activity, and is in some sense fundamental to the entire concept of what exception handling is and does.

      Consider: If you try to withdraw money from a bank, would you rather get a message back that "your deposit could not be accepted because your account is empty", or that "the database field 420032 contains a non-positive value"? Which of those are you prepared to take corrective action for?

      To any user of a subsystem, each error has to be handled using only contextual information that the user knows something about. If a method throws an IOException, but the caller had no idea that the method did I/O at all, then the caller won't be expecting to deal with an IOException, and won't even really know what to do about it if it happens. The caller can't even distinguish handling that IOException from another IOException that was thrown from other unrelated code nearby. On the other hand, if a caller calls a getFoo() method, and the method throws an IOException wrapped in a FooCouldNotBeGottenDueToMissingFileException which also contains a filename, then the caller at least knows what has happened if not necessarily exactly why. Someone trying to debug the problem with a debugger can look at the contained IOException and try to figure out what happened, but the calling code should just be able to handle a FooCouldNotBeGottenDueToMissingFileException with appropriate actions.

      Exception wrapping is very important for ensuring that full interface/implementation separation occurs, so that different subsystems don't need to know about how each other are implemented. This is true regardless of whether exceptions are checked or unchecked.

      Having all exceptions be unchecked would, however, eliminate one of the major tools that are useful in ensuring that a subsystem boundary does indeed wrap all exceptions in the manner I've just described: the fact that (in Java, anyway) not doing so triggers a compiler error. Without that, it would be very easy to have a method at the subsystem boundary accidentally fail to wrap an implementation-specific exception, and instead pass it on unmodified. The likely consequence of this would be that the caller probably wouldn't handle it, and it would be treated as a fatal exception when it wasn't supposed to be one, or ignored when it wasn't supposed to be.

      In general, the guideline that I (and many others) follow is this:

      At any subsystem boundary, the only checked exceptions that should be thrown are those defined in the interface to that subsystem. All other (non-fatal) exceptions should be wrapped in one of those. This allows the callers to deal with the interface to the subsystem only, and to distinguish between those specific categories of failures that are defined by the interface of the subsystem, without having to know how the subsystem is actually implemented or what libaries it might use internally.

      James Gosling discussed these issues in an interview a while back. I think what he said was very insightful, and I highly recommend that anyone who uses exceptions should read and understand what he said about the topic. The example he gave about test pilots, in particular, is a sobering one. I've had to work on high-criticality medical software before. The realization that someone might well die if the software failed to perform the correct handling action for a specific error caused me to think about error handling in an entirely different way. Sometimes handling the errors is as important, if not more important, than handling the "one true path" where no problems occur.

      Here's the link to the interview:





      1. Anonymous

      2. This way it gets down to every thing that is generic enough (visitor interface, generic function, etc) must declare an exception list. And visitor is an easy case there: all the methods are sort of supposed to throw the same exception. It gets worse with other interfaces, where different methods may (or may not) throw different exceptions.

        1. Hi Andrey.  In my proposal for doing checked exceptions better than Java does, I definitely didn't intend for a world in which every generic thing (visitor interface, generic function, etc.) must/usually declare an exception -- although it would be at the prerogative of the author of the interface.  That would be a pain, and it's a problem I see in the proposal by Brian Goetz.  When I suggested adding a throws statement within a block of code (vs the method declaration), it essentially means the author of the code accepts the possibility the exception could happen and to ignore it.  By ignoring it, it is effectively unchecked at that point -- the caller of this method wouldn't have to catch it (or explicitly ignore it) because it's not checked for that method.  Perhaps some proposal code would help:

          1. Hi David,

            This way of ignoring exceptions is definitely less annoying that catching them and doing nothing, but there're some issues I can see here:

            • The very presence of a special construct for ignoring exceptions, to me, points to a design flaw
            • This throws operator is not scoped otherwise than by block boundaries, which may cause errors when the code evolves
            • Although it generally seems more reasonable, I agree, having C++-style checked exceptions rather than Java-style (i.e. a method decides what's checked and what's not) does not seem to help here at all.
            1. Andrew,  It was a thrill to meet you quite by accident at the FB Open Academy event a week ago!  I re-pitched my idea for doing checked exceptions better than Java does, and you seemed to like it.  So this is a friendly reminder to please re-aquaint yourself with my comments on this wiki thread here and re-consider your stance -- it's been 2.5 years.  I don't think any solution will be perfect -- it's all a balance with competing design goals.  But I'm sure Kotlin can do better.

              Here's another code sample that illustrates my idea:

              1. The lambda part is tricky: that lambda might escape and the exception thrown from it will not be tracked.

                Otherwise I think it's a good idea.

        2. Anonymous

          Hi, Andrey.

          I understand the point you are trying to make, but I think that there is some confusion between the typical "cause" of the need for generic exception lists. In particular, I disagree with your statement that "every thing that is generic enough" must declare an exception list. Most generic things don't need to declare generic exception lists at all.

          What causes something need to have a generic exception list is not really its use of generic-like features. It is typically its use of executable code blocks as data (aka closures/callbacks/"higher order functions"). Generics are merely a way to accomplish that (and other things) in a statically type-safe manner.

          For instance, the Visitor pattern is basically a structure for supplying a set of related code blocks all together at the same time. THAT's why it needs generic exceptions: subtypes of it can override methods with arbitrary contents, and the expectation for its use is that all exceptions thrown by those blocks will be passed on to the caller. The fact that Visitor implementations may or may not be generic in other ways is irrelevant.

          Most types of generic data structures have no need of generic exceptions in throws clauses at all, either because they don't allow or encourage subclassing (e.g. ArrayList) or because all of the exceptions that they would ever need to throw will be descended from or wrapped within some known base type (e.g. a file parser, which presumably would throw IOExceptions or FileSyntaxExceptions, or subtypes of those, or instances of those wrapping other exceptions, from its methods if things went wrong).

          I have very rarely seen situations in which a class needed to throw a variety of generic exception types from multiple different kinds of methods, as you suggest. In general, people usually write code that expects clients to supply a small number of code blocks (typically zero) for a small number of distinct purposes, and hence there are usually a small number of exception types that could possibly be thrown by those blocks. I can't even remember the last time I saw the number of needed generic exception types rise above two.

          So while the issue you are mentioning is in principle real, my experience is that in practice, it doesn't really cause problems. When exception wrapping is used consistently, the number of exceptions that most methods can throw is very small (typically, one), and in most cases someone writing a generic abstract base class can determine at design time a set of exception supertypes that encompass all of the exceptions that the class could throw. Generic exception types are only needed in the relatively few cases where this is not possible, such as use of higher-order methods ('map', 'reduce', etc.) and similar data structures (Visitor, AbstractFactory<T>, Future<T>, etc.)

          Most of these constructs are so general-purpose that they don't need to take a wide variety of heterogenous code blocks as parameters (after all, if they did, they would no longer be general purpose!) and hence they don't need to be prepared to throw a wide variety of differing exception types from different methods. On the other hand, the more task-specific a class is, the more likely it is that its various methods will throw differing exceptions, but also the more likely it is that the set of exception supertypes it can throw can be known at design time (as in the IOException example above) without need of generics at all.

          1. Thanks for your comments.

            I would summarize my point as follows:
            if nearly every higher-order function (and these are not only map and reduce, and not only collections-related), visitor, factory, listener or other strategy I write needs to declare some generic throws clause, it's bad enough already, and this is the reason why we don't want checked exceptions.

            1. RE: "Hi David" -- FYI Mr. Anonymous wasn't me.  I suggest you force logins on Confluence.

              RE "if nearly every .... I write needs to declare some generic throws clause, it's bad enough already,..."  -- I completely agree! And in my proposal, such things wouldn't declare exceptions -- although admittedly if the author of one of those things deliberately wants to declare an exception, then it would be checked -- but I'd consider that bad practice in general. 

              1. Sorry about name confusion

            2. Anonymous

              Yes, statically typed exceptions (aka checked exceptions), like other static types, add syntax, as any Ruby/Python/Perl/etc. programmer can tell you. However, you have made static typing even stronger in Kotlin than it is in Java, with nullness checking, etc, despite the added syntax, presumably because you like the advantages that static typing brings you (more mistakes detected at compile time, fewer at runtime). It seems strange to me that you are so ready to ditch statically typed exceptions in favor of exclusively dynamically typed ones. This would be the one place that I can see where Kotlin's static typechecking is actually WEAKER than Java's.

              I understand that Jetbrains is concerned about the syntax associated with checked exceptions in higher-order functions. (It's not clear to me why this particular syntax is of such concern when similar syntax for typed parameters and return values is apparently considered OK.) Still, I notice that you are describing what you wish to GAIN by eliminating checked exceptions (simpler syntax), but you have not detailed the tradeoff of what will be LOST by taking this approach, or how you intend people to address those problems.

              Checked exceptions weren't created just to annoy programmers. They were created as a solution to a serious software maintenance problem that is especially nasty in large projects containing with many subsystems written by different authors (or companies): "How can a subsystem author ensure that clients of the subsystem at least try to handle certain critical error cases and don't just accidentally ignore them? Particularly when the interface, but not the implementation, of a subsystem is all that a client knows about it?"

              I am assuming here that the client programmers are dedicated programmers who actually want or need to have the program handle error cases as opposed to incompetent ones who see no problem with inserting empty "catch" blocks and doing whatever else is necessary to dodge error handling entirely. (The latter approach probably results in the program crashing the first time it encounters a problem, as per Weinberg's Law: "If builders built buildings the way programmers write programs, then the first woodpecker that came along would destroy civilization." Hopefully the software controlling the next airplane you ride in was not written with such a philosophy.)

              Given that the problem exists, how can it be successfully managed? I have yet to see an alternate approach to the "how can I be sure I've handled all errors" problem that isn't MORE syntactically ugly than statically typed exceptions.

              I've seen many people try alternate approaches, usually due to ignorance of Java or habits learned from other languages. I've seen case clauses or the equivalent, returning boolean, null, or enum status codes (and cascading them manually level-by-level up the call tree), throwing an unchecked exception with an "error type" code, instanceof checks on return values, etc. Hopefully these approaches are at least documented by the authors... but the documentation itself can be quite large, and tends to fall out of sync with the code since the compiler does no checking of it whatsoever.

              When I review my coworkers code and find such constructs, I regularly replace them with checked exceptions and typically realize a 50% or more decrease in total size of the error handling code, with less need to document it (since the code itself is clear) plus less need to test it (since the compiler will catch mistakes). In short, I achieve the typical benefits of using static typing over dynamic typing.

              Here are some relevant quotes (from http://gafter.blogspot.com/2007/05/removing-language-features.html) from people who have used .NET, which as you are undoubtedly aware, doesn't have checked exceptions.

              elizaroy writes:
              "...To realize why checked exceptions are so powerful it is educating to look at the mess that a big platform without checked exceptions becomes (.NET being a prime example). They unintentionally end up with APIs that throw exceptions that are not documented anywhere (since you cannot rely on documentation to properly reflect method behavior - compiler is not going to check verify your documentation). They also end up with complex software packages that just break on any I/O exception, for example. The programmer is not forced even to think what to do in a case of I/O exception. To continue I/O exception example (which is often cited by critics), I fully agree that reckless programmer will write a program that breaks on I/O exception even in a language that has checked exceptions. But it is not an intention of a language to completely prevent bad programs to be written (which is simply impossible in Turing-complete language), but to facilitate creation of good programs.
              I, for one, have come to believe though practice that checked exceptions is one such facilitating mechanism that, in addition to other static type checking facilities, leads to our ability to crease very complex software with high quality for a reasonable cost. And I believe we need more static type checking facilities, not less! Every piece of our method documentation (like return types, exceptions, nullness, etc) that we can have our compiler to check for us is a win in our battle with software complexity.

              fux11 writes:
              "elizarov i absolutely agree with you. we need more checking. if you dont want checked exceptions go to c#. i am chief of developers in my company an we have some .net and mostly java projects. checked exceptions make the java-projects far more stable and the error-handling is far better. you cannot trust documentation, the compiler has to force exception handling. i also agree with the comment about all the perl ruby etc. programmers who try to change features of java because the DONT UNDERSTAND them."

              Edison writes:
              "We develop systems using Java and .NET.
              We deal with checked exceptions encapsulating them in a framework exception (ugly but documented); but exceptions in .NET are totally undocumented (the Microsoft API does not document all possible exceptions, neither our programmers) and we have very big headaches with unexpected exceptions found in production phase.
              We desperately need checked exceptions in .NET; don't remove checked exceptions from Java. "

              With the above said, there are definitely some things that could be used to make use of checked exceptions less painful than those of Java. For instance, you could require "throws" exception type parameters to be placed at the end of a generic class's type parameter list, and could allow them to be omitted from uses of generic types if the user wanted to just use the default upper bound (RuntimeException in most cases). That would mean that the syntactic overhead of checked exceptions would mostly fall on people who have to WRITE methods like exception-safe visitors, etc. rather than on the majority of those who merely use them. (Typically far more people use generic classes than write them.) You could also replace the verbose "throws" keyword with some shorter syntax. You could even drop the ...Exception suffix on exception type names (putting in some compiler magic to automatically add them back when calling to/from Java code).

              Regardless, my main point is this: It seems to me that if you are going to propose that checked exceptions not exist in Kotlin, that you should also make a credible attempt at showing how Kotlin will solve the problems illustrated above, and show that your proposed solution will actually work in realistic instances of the cases mentioned above (large system, multiple authors, poor documentation, changes over time, can't see the source code of subsystems you didn't write, etc.) without creating code size or stability problems that are worse than those created by checked exceptions. The quotes above show that .NET's solution to these problems leaves something to be desired. Will yours have the same flaws? If not, why not?

              Under what circumstances is reducing the code size of a program worth increasing the risk that the program will crash unexpectedly? Note that not everybody will be using Kotlin to write an IDE.

              1. I get your point, but it is not as obvious as we would like. Please, refer to the quotes against checked exceptions given in the text.

                1. If you'll forgive the simplification, it seems that there was a move to dynamically typed languages in response to problems (particularly, but not only, verbosity) in the Java realisation of static typing.  Fortunately (at least from my perspective) there seems to now be a resurgence in statically typed languages, where these languages are providing better realisations of static typing that address many of the (valid) criticisms of Java-like static typing.

                  I see a parallel between (some of) the initial movement toward dynamic typing, and the contemporary moves away from checked exceptions.  David's call to arms to instead do checked exceptions better (rather than not at all) resonates with me.  I like the core of David's suggestion, but I am not enamoured with the first pass at syntax.  As I understand David's proposal, moving the brace before or after throws clause dramatically changes the interpretation ; I don't feel this is conducive to quick and accurate parsing (by humans).  The below is effectively identical to Dmitry's suggestion, but perhaps it goes some way to addressing the "quotes against checked exceptions given in the text" (at any rate, I didn't feel like throwing away the text after seeing Dimtry's comment, perhaps you'll forgive the verbose "+1", if not ... shrug).

                  Consider an additional keyword "propagates" together with adopting the familiar "throws".  Rather than checked being a property of the exception type, an exception is checked (or not) only in the context of a given declaring method (as per David's suggestion, as I understood it; perhaps a little c++ like).

                  I propose that functions would use "throws" to declare that the identified Exception(s) are exceptional conditions that the caller should consider and could reasonably be expected to recover from (in the context of directly exercising the function at hand).  Conversely "propagates" would be used to declare that while the function body encounters the named Exception(s) in a checked context, from the perspective of consumers of the function the identified Exceptions are implementation details that most direct callers are not expected to address.

                  i.e. "propagates" makes a checked exception unchecked, for where the method implementer makes the decision that the Exception in question doesn't make sense as a checked exception of the API being defined, nor can it be dealt with usefully in the method body.

                  "propagates" can only list Exceptions in the method body that are encountered as checked (listing an arbitrary exception would not compile).  Conversely, the "throws" clause can always declare any Exception (this allows the tunnelling pattern that the Rod Waldhoff article noted, without any wrapping/unwrapping); this provides the symmetry such that "throws" can make an Exception encountered in an unchecked context checked.

                  Some examples:

                  For your Appendable example, I suggest that you wouldn't expose implementation detail exceptions (IOException) at this API level; if the adapter (implementing Appendable) could not deal with an IOException generated by consumed code, it would simply "propagate" it as unchecked.  No need to pollute up the call hierarchy, we can flip to unchecked as soon as the exception becomes an implementation detail from the perspective of the consuming code.  I'm assuming your example was with regards to novel code written in Kotlin++ (i.e. with checked exceptions), rather than the Java interop issue.   The same applies to your comment with respect to Visitor.

                  As a generalisation, the further the distance from the generation of an exception, the more likely that propagating it as unchecked is likely to be appropriate.  As a result we side step the scalablity issue (cf. the Anders Hejlsberg interview you referenced), as we don't collect checked exceptions as we move up the call hierarchy food chain, as soon as a given exception becomes an implementation detail, it is propagated as unchecked, with relatively little boilerplate.

                  I personally see the API versioning "issue" (again cf. the Anders Hejlsberg interview you referenced) introduced by checked exceptions a key part of their value, rather than being a problem to be solved.  Personally, I want to know when a consumed API can now throw a new exception that I can reasonably be expected to deal with (even if it is only to make the assessment that there is nothing sane I can do beyond propagate it up the call hierarchy).  The alternative, where code simply throws a new exception 'silently', only to be discovered at runtime seems highly undesirable to me.

                  The ability to flip treatment between checked and unchecked for a given exception in a given call hierarchy would seem to support the "exception tunnelling" Rod Waldhoff advocates in the article you reference, without any need for any boxing/unboxing.

                  I find it is interesting that you quote Joshua Bloch "don't ignore exceptions" in arguing for the best way (I contend) to have exceptional conditions ignored - by removing help from the compiler to alert the developer to exceptions whose treatment should be considered within a given block of code (a previous Anonymous commentator made the same point).

                  I am unconvinced by the argument that checked exceptions are bad because some programmers smother them - are we seriously expected to believe those same developers who smother an exception to "come back to it later, but never do", are going to review (the quite likely undocumented) unchecked exceptions generated by every function they consume and deal with those that could be well addressed locally, and/or write comprehensive unit tests that cover these circumstances?  Code that simply smothers exceptions hopefully wouldn't make it past the code review or your pair through to commit.

                  In response to Andrey's commented that the "very presence of a special construct for ignoring exceptions [...] points to a design flaw" I would observe that this does naught more than make a specific exception behave as Kotlin currently proposes to treat all exceptions.  It seems better to provide an expressive (yet terse) mechanism to declare that an exception circumstance has been considered by the developer and deemed, in this context, to not have any useful local recovery.  I didn't understand the block scoping concern in the same comment - perhaps you can expand?

                  It seems to me that only supporting propagation as unchecked at the method level is sufficient; for cases where finer granularity is required, method decomposition seems unlikely to be undesirable (power to the double negative I say).

                  Deferring all checked exceptions to a global handler might work for a significant portion of web development work, but it just doesn't cut it for mission critical applications (IMHO).

                  I perceive three key issues with checked exceptions in Java:

                  1. The property of checked vs unchecked being a property of the Exception (by virtue of it superclass).
                  2. Inability (prior to Java 7) to address multiple exceptions in a single block without casting an overly broad net.
                  3. The poor examples in the core libraries

                  This approach only deals with the first, the remaining two are left as an exercise for the reader.  I suggest it is important for Kotlin to support multi-catch of some form, to allow consumers to deal with current contracts gracefully while still receiving help from the compiler when consumed methods are changes to produce additional error conditions (not sure what the "when" syntax/semantics would look like - specifically with checked exceptions you would want the compiler to complain when the author did not explicitly address a given exception type, so catching Exception and then switching/pattern matching inside the catch block seems deficient...).

                  It should not be surprising that the first huge library to use checked exceptions was going to help us learn a lot of lessons, unfortunately many hold up the use of a pattern in the Java libraries as an argument that the pattern is best practice (or to support the argument that checked exceptions are beyond redemption, as the authors of said library didn't always get it right within the constraints of the system they had).

                  With regards to Java interop, a Java method that declares a checked exception maps to the same in Kotlin.  This does have the downside that some (many?) APIs will inherit non-ideal interfaces from Java.  These will need to be wrapped in Kotlin (perhaps using extension functions), or the calling code will need to "propagate" appropriately.

                  Perhaps such an approach minimises the overhead of checked exceptions in any consumed libraries to those who dislike them.  (I contend) It would be a compelling differentiator with respect to (for example) Scala for those who value checked exceptions.

                  1. We have started investigating the possibilities of making checked exceptions better and possibly integrating them into Kotlin design. It will take us some reading/experimenting, though.

                    1. -1

                      I’d much rather Kotlin had unchecked exceptions.  Checked exceptions would introduce a lot of complexity and I don’t think they would bring enough benefit to be worth it.

                      Checked exceptions have been in Java for 15 years and people still can’t agree whether they are a good idea.  And I think it’s significant that no other language has copied them and no-one seems to complain that their language doesn’t have them.

                      Wouldn’t it be better for Kotlin to avoid such a controversial feature?

                      1. Some people from .NET world are complaining about having no checked exceptions.

                        I'm pretty much convinced that the Java's way of doing checked exceptions is a no-go. I'm not convinced there isn't any better way of doing them.

                        I totally understand the concern about complexity of the feature. A bigger concern is that it seems to interact with too many other features.

                        So, there's something to think about. That's why we are not adding this feature to the language, but merely investigating the possibility. I personally am not a great believer in it (smile)

                        1. As a .Net developer I can affirm that the vast majority of people are perfectly happy without checked exceptions.

  5. I see "throw X(9)" rather than Java's "throw new X(9)" which must be a contructor call.  How to I throw an existing exception instance rather than a new one?  Although not common, some of my larger code bases construct exceptions at different places than they are thrown for various reasons, or sometimes I refactor out shared exception construction code into a utility method when a class needs to wrap exception type X and rethrow as type Y for API conformance.

    1. val x : Exception = ... 
      throw x
  6. Anonymous


    Instead of forbidding peaple to use checked exception you may let them decide by themself to use checked exception or not on method level.

    e.g. foo(File f) throws IOException - anyone who call this method must deal with IOException some way,

    but bar(File f) unchecked IOException - may throw IOException (which is checked) BUT for caller this IOException will be unhecked.

    so, if I call some method which throws somehing I don't won't to deal with I can just put this exceptions into "unckeched" section of method signature

    and also I can put IOException into "throws" section, so caller will decide by himself what to do.


    Dmitry Mamonov

    1. A similar approach has been discussed above. Please, refer to that discussion.

        1. This does not look feasible in an extensible program (i.e. the one that supports plug-ins or something similar).

  7. For a (very) different view on error handling: has anybody given some thought on something like Common Lisp's condition system? Or some form of resumable exceptions?

    1. Such mechanisms rely on the runtime support that is not available on the JVM. Emulating these mechanisms makes many compatibility scenarios very difficult.

      1. Yeah, I thought compatibility would be the main problem... Oh, well. Error checking always seemed somewhat inflexible to me, so with all these new languages cropping up with some cool new ideas (depending on who you ask :)), I wondered if someone would take a stab at some different error handling techniques.

  8. Hi,
    did you consider less verbose syntax for try catch finaly blocks? I think it will be great if variables from try block are visible from catch and finally blocks (like you did with do while loop). Here is an example:
    current syntax:

    desired syntax:

    1. This is an interesting feature proposal. Mind to file an issue to http://youtrack.jetbrains.com/issues/KT? Thanks

        1. Yes, as a function: see use()

  9. Rethrowing an exception is not supported?

    1. Why not? Just say

      throw e

      1. I asked about 

        Will this feature?

        1. Doesn't seem to be necessary...

  10. Handling More Than One Type of Exception in a single catch block

    Is it available or will it available in the future?

    could be something like:

    1. You can do it like this now:

      try { 
      } catch (e: Throwable) { 
        when (e) { 
          is IOException -> {...} 
          is ParseException -> {...} 
          else -> throw e 

      Handling this specially is not on our list of priorities as very few users seem to want it

  11. I see one possible problem with not having a checked InterruptedException or InterruptedIOException, as catching it clears thread's interrupted flag, ultimately modifying precious state. For instance, the developer did a catch on generic Exception from some 3rd party library, to do a harmless log-and-rethrow, but ended up causing the app to hang, because somewhere there is a

    Is there a solution to this in Kotlin? I would personally prefer if Java didn't clear the interrupted flag when throwing InterruptedException. Some of our 3rd party library integration code is a mess because of it. Maybe Kotlin could somehow help suppress this behaviour? Cheers.

    1. I don't know of a way of changing this behavior of Java. A simple workaround for some situations would be to use a custom volatile flag instead of isInterrupted()

      1. Thanks. That would work for interrupting only some logic on my side of code. Would not help with interrupting IO (e.g. blocking socket accept), or third party library code, especially heavily threaded ones.

        The "good" news is that, a checked InterruptedException in Java does not really solve this problem either, only helps that tiny-little bit. So I doubt that lack of checked exceptions in Kotlin would be of any real hindrance in this respect.