- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create custom errors in Golang
Golang provides us with different approaches that we can use to print custom errors. We will explore two such approaches in this article.
The first approach requires us to make use of the error.New() function which will create a new error, and we can even pass a string of our choice inside it as an argument.
Example 1
Consider the code shown below.
package main import ( "errors" "fmt" "math" ) func areaOfCircle(radius float64) (float64, error) { if radius < 0 { return 0, errors.New("Area calculation wrong, the radius is < zero") } return math.Pi * radius * radius, nil } func main() { radius := -10.0 area, err := areaOfCircle(radius) if err != nil { fmt.Println(err) return } fmt.Printf("Area of circle %0.2f", area) }
In the above code, we are trying to find the area of the circle, but we are passing the radius as negative which will return our error that we have created inside the areaOfCircle function.
Output
If we run the command go run main.go on the above code, we will get the following output in the terminal.
Area calculation wrong, the radius is < zero
Example 2
The other approach is to make use of fmt.Errorf() with the help of which we can pass formatted values as well.
Consider the code shown below.
package main import ( "fmt" "math" ) func areaOfCircle(radius float64) (float64, error) { if radius < 0 { return 0, fmt.Errorf("Area calculation wrong, the radius %0.2f is < zero", radius) } return math.Pi * radius * radius, nil } func main() { radius := -10.0 area, err := areaOfCircle(radius) if err != nil { fmt.Println(err) return } fmt.Printf("Area of circle %0.2f", area) }
Output
If we run the command go run main.go on the above code, we will get the following output in the terminal.
Area calculation wrong, the radius -10.00 is < zero