Run-time Exceptions and Panic

This lesson explains runtime errors in detail and how a program responds to them.

We'll cover the following

Run-time panic

When an execution errors occur, such as attempting to index an array out of bounds or a type assertion failing, the Go runtime triggers a run-time panic with a value of the interface type runtime.Error, and the program crashes with a message of the error. This value has a RuntimeError() method, to distinguish it from a normal error.

Panic can also be initiated from code directly: when the error-condition (which we are testing in the code) is so severe and unrecoverable that the program cannot continue, the panic function is used, effectively creating a run-time error that will stop the program. It takes one argument of any type, usually a string, to be printed out when the program dies. So, panic resembles the throw statement from Java or C#. The Go runtime takes care to stop the program and issue some debug information. How it works is illustrated below:

Get hands-on with 1400+ tech skills courses.