Handling Exceptions with When Clause in Catch
📖 Scenario: Imagine you are writing a program that processes user input numbers. Sometimes, the input might cause errors like division by zero or invalid format. You want to catch these errors but handle them differently based on the error details.
🎯 Goal: You will create a program that uses try-catch blocks with when clauses to catch exceptions only when certain conditions are met.
📋 What You'll Learn
Create a variable called
numbers with the values 10, 0, and 5.Create a variable called
index and set it to 1.Use a
try block to divide 100 by the number at numbers[index].Use a
catch block with a when clause to catch DivideByZeroException only when the exception message contains the word zero.Use another
catch block with a when clause to catch IndexOutOfRangeException only when index is greater than 2.Print the appropriate messages inside each
catch block.Print
"Division result: {result}" if no exception occurs.💡 Why This Matters
🌍 Real World
In real programs, you often need to handle errors carefully depending on the exact problem. Using <code>when</code> clauses helps you write cleaner and more precise error handling.
💼 Career
Understanding advanced exception handling is important for writing robust software that can handle unexpected situations gracefully, a key skill for software developers.
Progress0 / 4 steps