CJCoding With Joseph

Catch An Invalid Cast

An object variable can hold any type, but unboxing it to the wrong type throws an InvalidCastException. Read one line from input. If the line is exactly num, store the boxed integer 7 in an object; otherwise store the string "seven" in it. Then try to unbox it with (int)obj. If the cast succeeds, print Value: <n> (for example Value: 7). If it throws InvalidCastException, print Error: bad cast. Use top-level statements with try/catch (no Main method needed).

Input num prints: Value: 7
Input seven prints: Error: bad cast

Expected Output:

Value: 7
Topics:
Exceptions
๐Ÿ“ฅ Auto-Input:
num\n
This input is automatically fed to your program's stdin
Code Editor
1
Tab to indent ยท Ctrl+Enter to run ยท Ctrl+Space to expand shortcuts (cw, cr, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.