duanlu5055 2014-04-25 05:18
浏览 28

GO lang异常处理

I am new to go lang. How to achieve subtype inheritance in GO and handle exceptions in it? I am trying something to this but somehow I am not able to get it to work.

import java.io.*;
import java.rmi.*;

class class1
{
    public void m1() throws RemoteException
    {
        System.out.println("m1 in class1");
    }
}

class class2 extends class1
{
    public void m1() throws IOException
    {
        System.out.println("m1 in class2");
    }
}

class ExceptionTest2
{
    public static void main(String args[])
    {
        class1 obj = new class1();

        try{
            obj.m1();
        }
        catch(RemoteException e){
            System.out.println("ioexception");
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongxiezhuo8852 2014-04-25 06:52
    关注

    As people already has pointed out, Go is very different from Java.
    That means you will not have something "very much similar" to the Java code.

    Embedding instead of inheritance

    Go does not have inheritance as you might be familiar with it. The closest you might find is called embedding.

    And while an embedded method might be shadowed by a method of the parent and act as a sort of override, this is not a common way to solve your programming tasks in Go.

    Errors instead of Exceptions

    Panics are not to be used as exceptions. If you want to write Go code, you return errors to inform the calling function/method that something went wrong.

    What your code might look like in Go:

    package main
    
    import (
        "errors"
        "fmt"
    )
    
    var (
        RemoteError = errors.New("A remote error occured")
        IOError     = errors.New("An IO error occured")
    )
    
    type Struct1 struct{}
    
    func (s *Struct1) m1() error {
        fmt.Println("m1 in Struct1")
        return nil // or RemoteError
    }
    
    type Struct2 struct {
        Struct1
    }
    
    func (s *Struct2) m1() error {
        fmt.Println("m1 in Struct2")
        return nil // or IOError 
    }
    
    func main() {
        s1 := &Struct1{}
    
        err := s1.m1()
        if err != nil {
            fmt.Println(err.Error())
        }
    }
    

    Output:

    m1 in Struct1
    

    Playground: http://play.golang.org/p/VrhvtQDXCx

    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏