Skip to content

Commit

Permalink
defer function
Browse files Browse the repository at this point in the history
  • Loading branch information
Himanshuxone committed Oct 26, 2016
1 parent 8a304b8 commit ec3d49f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
21 changes: 21 additions & 0 deletions catchError.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main
import "fmt"

func main() {
fmt.Println(safeDiv(6,0));
fmt.Println(safeDiv(6,3));
}

// create a function safeDiv to divide two numbers to generate an exception divide the number by zero and catch the exception using recover() function

func safeDiv(num1, num2 int) int{
// to execute the recover() function at the end of completing division use defer keyword
// below function is used to catch an error if occurs
defer func() {
fmt.Println(recover())
}()

solution := num1 / num2;
return solution;

}
14 changes: 14 additions & 0 deletions deferFunction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main
import "fmt"

func main() {
// defer key word is used to execute any function at the last or after the execution of all contents in the main
// here defer will execute printOne() function after printTwo() even the printOne function is written before the latter functions
// hence the defer is used for wrapping things up like closing a databse connection after the query executed successfully
// defer makes it confirm that the function will execute at the end after everything executed succesfully
defer printOne()
printTwo()
}

func printOne(){ fmt.Println(1) }
func printTwo(){ fmt.Println(2) }

0 comments on commit ec3d49f

Please sign in to comment.