0

I want to add code to throw an error that requires the "catch let printerErrorsecond" and the last catch block to handle an error. I have tried updating the value for the toPrinter parameter to a number of values without any luck. I also tried a number of else if statements and cannot seem to get either of the last two catch blocks to handle the errors. It seems like a case for both could be added in the PrinterError enum but after several attempts I could not resolve the issue. Any code based resolutions you can provide the better!

enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    } else if printerName == "Fire" {
        throw PrinterError.onFire
    } else if printerName == "Empty" {
        throw PrinterError.outOfPaper
    }
    return "Job sent"
}

do {
    let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
    print(printerResponse)
} catch PrinterError.onFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}
// Prints "Job sent"
mrmillmill
  • 36
  • 9
  • This works fine for me. When I use `toPrinter: "Empty"`, I see the message: "Printer error: outOfPaper." – dalton_c Feb 01 '22 at 21:39
  • It's worth noting that the last catch block will never be called because your function only throws errors of type `PrinterError`. – dalton_c Feb 01 '22 at 21:40
  • @daltonclaybrook Perfect thank you for the feedback! After posting I was able to get that block to fire as well. – mrmillmill Feb 03 '22 at 00:45
  • @daltonclaybrook You are a champ I appreciate the feedback on both catch blocks. I was not sure if that last block would ever fire or how to get it to fire. Any recommendations on how to get that last block to fire? What would I need to change? – mrmillmill Feb 03 '22 at 00:46

1 Answers1

0

try to implement it by this way

enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
    case deFault
    case noHandeling
}

func send(job: Int, toPrinter printerName: String) throws -> String {
    switch printerName {
    case PrinterError.outOfPaper.localizedDescription:
        print("outOfPaper")
        return PrinterError.outOfPaper.localizedDescription
    case PrinterError.noToner.localizedDescription:
        print("noToner")
        return PrinterError.noToner.localizedDescription
    case PrinterError.onFire.localizedDescription:
        print("onFire")
        return PrinterError.onFire.localizedDescription
    default:
        print("default")
        return PrinterError.deFault.localizedDescription
    }
}


    do {
        try send(job: 100, toPrinter: "AAA")
    } catch {
        print(error.localizedDescription)
    }
Woop
  • 99
  • 2
  • 11