Exceptions are special classes used to represent a potentially fatal error state. Each exception class includes a function to print the stacktrace to the output and can also contain a message.
Throwing and Catching exceptions
In order for an exception to occur, an instance of Exception (or one of its child classes) must be thrown using the throw keyword. This exception will move up the call stack until a try-catch block is found:
try {
throw new Exception()
} catch (e : Exception) {
e.printStacktrace()
}
A try-catch block can also have multiple catch statements and can even catch the same exception multiple times:
try {
throw new FooException()
} catch (e : FooException) {
throw e
} catch (e : FooException) {
throw e
} catch (e : Exception) {
e.printStacktrace()
}
Exceptions and Functions/Constructors
Sometimes, a function or constructor shouldn't handle any exceptions it throws. A function in a library, for example, may not know the entire context in which the exception occurred and may require the caller to provide more information. In this case, a function or constructor declaration needs to be followed by the throws keyword followed by all the exceptions it can throw:
func doFooThing(), throws Exception {
throw new Exception()
}
Any function or constructor that doesn't handle a certain exception needs to be thrown this way. This includes the callers of those functions and so on until a try-catch block is encountered.
Overview
Exceptions are special classes used to represent a potentially fatal error state. Each exception class includes a function to print the stacktrace to the output and can also contain a message.
Throwing and Catching exceptions
In order for an exception to occur, an instance of
Exception
(or one of its child classes) must be thrown using thethrow
keyword. This exception will move up the call stack until atry
-catch
block is found:A
try
-catch
block can also have multiplecatch
statements and can even catch the same exception multiple times:Exceptions and Functions/Constructors
Sometimes, a function or constructor shouldn't handle any exceptions it throws. A function in a library, for example, may not know the entire context in which the exception occurred and may require the caller to provide more information. In this case, a function or constructor declaration needs to be followed by the
throws
keyword followed by all the exceptions it can throw:Any function or constructor that doesn't handle a certain exception needs to be thrown this way. This includes the callers of those functions and so on until a
try
-catch
block is encountered.