Exceptions provide a much needed mechanism for supporting error handling. They do this be allowing control to pass back up the call stack under error situations.
A throw statement is how an exceptional situation is signaled and has the form:
throw expression;
The expression is evaluated then the resulting entity is thrown
. That is control leaves the current pattern and passes to the appropriate catch handler somewhere in the call stack above. When an exception leaves a pattern the object instantiated by that invocation is incomplete and all references to it are invalid.
In order to insure safety it is necessary to know the type of any entity which may be thrown by a pattern. To accomplish this pattern declarations and pattern types may be appended with throws clauses indicating what types of entities may be thrown. These have the from:
throws type-1, type-2, ..., type-n
A throws clause indicates that a pattern may throw any of the listed types or a type compatible with those types. If no throws clause is present then no entities may be thrown from the pattern. When overloading or assigning patterns the throws clauses must be compatible. A throws clause is compatible with another if all the types listed by it are compatible with one of the throwable types of the other.
When invoking a pattern which may throw exceptions one may want to handle some or all of the exceptions declared thrown by that pattern. This is done with a try catch statement. They have the form:
try(a :short)
statement
catch( identifier : type )
statment
Any number of catch clauses may be listed but there must be at least one. When an exception is thrown by code within the try's statement (which may be a block statement) control may pass to one of the catch clauses. After the catch's statement is executed control continues after the try catch statement barring other exception situations. A catch clause is selected based on the type of the thrown entity at runtime. Catch clauses are checked in order from top to bottom to see if the thrown entity is compatible with the declared type to be caught. If it is the control passes to that catch clause. Otherwise catch clauses after it are checked. If the end of the catch clause list is reached without having found a catch to handle the exception then the exception is thrown from the statement.
Try catch statements can take a declaration list just as most other control structures. These variables are then accessible to the contents of the try and the catch clause.