Menu
Coddy logo textTech

Recap - Handling Problems

Part of the Fundamentals section of Coddy's GO journey — lesson 109 of 109.

challenge icon

Challenge

Easy

Let's practice error handling in Go with a simple temperature conversion program.

Your task is to implement a function that converts temperatures from Celsius to Fahrenheit, with proper error handling.

Complete the celsiusToFahrenheit function that:

  • Converts a Celsius temperature to Fahrenheit using the formula: F = C × 9/5 + 32
  • Returns an error if the temperature is below absolute zero (-273.15°C)

For the error message, you must return exactly: "Error: temperature below absolute zero"

The main function contains test cases to verify your implementation.

Try it yourself

package main

import (
	"errors"
	"fmt"
)

// celsiusToFahrenheit converts Celsius to Fahrenheit
// Returns an error if the temperature is below absolute zero (-273.15°C)
func celsiusToFahrenheit(celsius float64) (float64, error) {
	// TODO: Implement the conversion logic
	// 1. Check if temperature is below absolute zero (-273.15°C)
	// 2. If valid, convert using the formula: F = C × 9/5 + 32
	// 3. Return appropriate value and error
	return 0, nil
}

func main() {
	// Test valid temperature
	fmt.Println("Converting 25°C to Fahrenheit:")
	fahrenheit, err := celsiusToFahrenheit(25)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("25°C = %.2f°F\n", fahrenheit)
	}

	// Test another valid temperature
	fmt.Println("\nConverting 0°C to Fahrenheit:")
	fahrenheit, err = celsiusToFahrenheit(0)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("0°C = %.2f°F\n", fahrenheit)
	}

	// Test invalid temperature (below absolute zero)
	fmt.Println("\nConverting -300°C to Fahrenheit:")
	fahrenheit, err = celsiusToFahrenheit(-300)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("-300°C = %.2f°F\n", fahrenheit)
	}
}

All lessons in Fundamentals