โ Back to Exceptions
Question 700
Catch An Invalid Cast
Catch An Invalid Cast
Anobjectvariable can hold any type, but unboxing it to the wrong type throws anInvalidCastException. Read one line from input. If the line is exactlynum, store the boxed integer7in anobject; otherwise store the string"seven"in it. Then try to unbox it with(int)obj. If the cast succeeds, printValue: <n>(for exampleValue: 7). If it throwsInvalidCastException, printError: bad cast. Use top-level statements withtry/catch(noMainmethod needed). Input num prints: Value: 7 Input seven prints: Error: bad cast
Expected Output:
Value: 7
Topics:
Exceptions
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.