Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

go中的异常处理机制

为了保证程序不会因为一个异常而导致停摆,同时又不像其它语言那么啰嗦,对go语言的异常机制的简单理解实践一下吧

package main

import "fmt"

func divide(a int,b int,isPanic bool) int  {
	//,类似于 java try catch ,,通过panic抛出异常 recover 捕获,
	if isPanic{
		defer func() {
			if err := recover(); err != nil{
				fmt.Println(err)
			}
		}()
	}
  //可以自行捕获异常,自定义异常信息
	/*if b==0{
		panic("除数不能等于0")
	}*/
	c := a/b
	return c
}

func main() {
	divide(3,0,true)
	fmt.Println("我的天,一切运转正常")
}

Out1:

runtime error: integer divide by zero
我的天,一切运转正常

Out2:

自定义异常信息
除数不能等于0
我的天,一切运转正常

如果没有recover,程序不能正常往下执行,就此打住了;