Lesson 31 of 34

Exceptions: பிழைகளைக் கையாளுதல்Exceptions: Handling Errors

10 min 30 XP

Program இயங்கும்போது பிழை (exception) வந்தால் அது நின்றுவிடும். try உள்ளே ஆபத்தான code-ஐ வைத்து, catch மூலம் பிழையைப் பிடித்து கையாளலாம். finally எப்போதும் இயங்கும்.

When an error (exception) happens while a program runs, it crashes. Put risky code inside try and handle the error in catch. finally always runs.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

throw மூலம் நாமே ஒரு exception-ஐ எழுப்பலாம், உதாரணமாக தவறான மதிப்பு வந்தால்.

You can raise an exception yourself with throw, for example when a method receives a bad value.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Checked exceptions (IOException போன்றவை) compile நேரத்திலேயே கையாள வேண்டும்; unchecked (RuntimeException) அப்படி அல்ல. இந்த வேறுபாடு interview-ல் கேட்கப்படும்.

Checked exceptions (like IOException) must be handled at compile time; unchecked ones (RuntimeException) need not be. Interviews love this difference.

Challenge

+30 XP

இரண்டு மதிப்புகளை text-ஆகப் படித்து (sc.next()), Integer.parseInt மூலம் எண்ணாக மாற்றி வகுத்தல் விடையை print செய்யுங்கள். எண் அல்லாதவை வந்தால் "Invalid number", 0-ஆல் வகுத்தால் "Cannot divide by zero" என்று print செய்யுங்கள். Input: 20 4 → Output: 5

Read two values as text (sc.next()), convert them with Integer.parseInt and print the first divided by the second. Print "Invalid number" if either isn't a number and "Cannot divide by zero" when dividing by 0. Input: 20 4 → Output: 5

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.