GO lang exception handling

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");
        }
    }
}

There are no exceptions in go, errors are returned as values.

You can learn more about the concept on the tour chapter about errors

2 Likes

Why trying to do things not supported by the language ?

There is no inheritance in Go. It supports Object composition. Also there is no exception but errors.
You java code in go Go looks like this:

package main
import "fmt"

type MyInterface {
  M1() Error
}

type Class1 struct {
}

func (p *Class1) M1() Error {
  fmt.Println("m1 in class1");
}

type Class2 struct { 
}

func (p *Class2) M1() Error {
  fmt.Println("m1 in class2");
}

func main() {
  obj := &Class1{}
  err := obj.M1()
  if err != nil {
     fmt.Println("ioexception")
  }	
}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.