|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | +) |
| 7 | + |
| 8 | +type CustomError struct { |
| 9 | + Message string |
| 10 | +} |
| 11 | + |
| 12 | +func (e *CustomError) Error() string { |
| 13 | + return e.Message |
| 14 | +} |
| 15 | + |
| 16 | +func main() { |
| 17 | + // Ejemplo 1: División por cero |
| 18 | + result, err := divideNumbers(10, 0) |
| 19 | + if err != nil { |
| 20 | + fmt.Println("Error:", err) |
| 21 | + } else { |
| 22 | + fmt.Println("Resultado:", result) |
| 23 | + } |
| 24 | + |
| 25 | + // Ejemplo 2: Acceso a índice fuera de rango |
| 26 | + numbers := []int{1, 2, 3} |
| 27 | + value, err := getValueAtIndex(numbers, 5) |
| 28 | + if err != nil { |
| 29 | + fmt.Println("Error:", err) |
| 30 | + } else { |
| 31 | + fmt.Println("Valor:", value) |
| 32 | + } |
| 33 | + fmt.Println("****************************** Reto ***************************************") |
| 34 | + // Llamada a la función processParams con diferentes casos |
| 35 | + err = processParams(10, 2) |
| 36 | + handleError(err) |
| 37 | + |
| 38 | + err = processParams(0, 5) |
| 39 | + handleError(err) |
| 40 | + |
| 41 | + err = processParams(10, 0) |
| 42 | + handleError(err) |
| 43 | + |
| 44 | + err = processParams(-5, 3) |
| 45 | + handleError(err) |
| 46 | + |
| 47 | + err = processParams(8, 4) |
| 48 | + handleError(err) |
| 49 | + |
| 50 | + fmt.Println("Ejecución finalizada") |
| 51 | +} |
| 52 | + |
| 53 | +func divideNumbers(a, b int) (int, error) { |
| 54 | + if b == 0 { |
| 55 | + return 0, fmt.Errorf("No se puede dividir por cero") |
| 56 | + } |
| 57 | + return a / b, nil |
| 58 | +} |
| 59 | + |
| 60 | +func getValueAtIndex(numbers []int, index int) (int, error) { |
| 61 | + |
| 62 | + if index < 0 || index >= len(numbers) { |
| 63 | + return 0, fmt.Errorf("Índice fuera de rango: %d", index) |
| 64 | + } |
| 65 | + |
| 66 | + return numbers[index], nil |
| 67 | +} |
| 68 | + |
| 69 | +// Función que procesa parámetros y puede lanzar diferentes tipos de excepciones |
| 70 | +func processParams(a, b int) error { |
| 71 | + if a == 0 { |
| 72 | + return errors.New("No se puede procesar con el valor 'a' igual a cero") |
| 73 | + } |
| 74 | + |
| 75 | + if b == 0 { |
| 76 | + return fmt.Errorf("No se puede procesar con el valor 'b' igual a cero") |
| 77 | + } |
| 78 | + |
| 79 | + if a < 0 || b < 0 { |
| 80 | + return &CustomError{Message: "No se pueden procesar valores negativos"} |
| 81 | + } |
| 82 | + |
| 83 | + // Procesamiento correcto |
| 84 | + result := a / b |
| 85 | + fmt.Printf("Resultado: %d\n", result) |
| 86 | + return nil |
| 87 | +} |
| 88 | + |
| 89 | +func handleError(err error) { |
| 90 | + if err != nil { |
| 91 | + fmt.Println("Tipo de error:", err) |
| 92 | + } else { |
| 93 | + fmt.Println("No se ha producido ningún error") |
| 94 | + } |
| 95 | +} |
0 commit comments