47 lines
2.3 KiB
Markdown
47 lines
2.3 KiB
Markdown
## Raise Statement
|
||
|
||
In AVAP, the raise statement is used to throw an exception. The syntax for the raise statement is as follows:
|
||
|
||
```javascript
|
||
raise [expression ["from" expression]]
|
||
```
|
||
|
||
If no expressions are present, raise re-raises the currently handled exception, also known as the active exception. If there is no active exception, a `RuntimeError` is raised indicating that it is an error.
|
||
|
||
Otherwise, raise evaluates the first expression as the exception object. It must be a subclass or an instance of `BaseException` . If it is a class, the exception instance is obtained when needed by creating an instance of the class without arguments.
|
||
|
||
The type of the exception is the instance of the exception class, and the value is the instance itself.
|
||
|
||
The `from` clause is used for exception chaining: if provided, the second expression must be another class or instance of exception. If the second expression is an exception instance, it will be attached to the raised exception as the `__cause__` attribute (which is modifiable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the `__cause__` attribute. If the raised exception is not handled, both exceptions will be printed.
|
||
|
||
```javascript
|
||
startLoop()
|
||
try:
|
||
print(1 / 0)
|
||
except Exception as exc:
|
||
raise RuntimeError("Something went wrong") from exc
|
||
endLoop()
|
||
```
|
||
|
||
A mechanism works implicitly if a new exception is raised while an exception is already being handled. An exception may be handled by an `except` or `finally` clause, or a `with` statement. The previous exception is then attached as the new exception’s `__context__` attribute:
|
||
|
||
```javascript
|
||
startLoop()
|
||
try:
|
||
print(1 / 0)
|
||
except:
|
||
raise RuntimeError("Something went wrong") from None
|
||
endLoop()
|
||
```
|
||
|
||
Exception chaining can be explicitly suppressed by specifying `None` in the `from` clause:
|
||
|
||
```javascript
|
||
startLoop()
|
||
try:
|
||
print(1 / 0)
|
||
except:
|
||
raise RuntimeError("Something went wrong") from None
|
||
endLoop()
|
||
```
|