Question

why should we program for exceptions? Using code snippets, provide an example situation where programming for...

why should we program for exceptions?
Using code snippets, provide an example situation where programming for exceptions gives value to the end user.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:) Exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. The

class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found within this method.
static int divideByZero(int a, int b){

// this statement will cause ArithmeticException(/ by zero)
int i = a/b;

return i;
}

// The runTime System searches the appropriate Exception handler
// in this method also but couldn't have found. So looking forward
// on the call stack.
static int computeDivision(int a, int b) {

int res =0;

try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}

// In this method found appropriate Exception handler.
// i.e. matching catch block.
public static void main(String args[]){

int a = 1;
int b = 0;

try
{
int i = computeDivision(a,b);

}

// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
}

please don't forget to like

Add a comment
Know the answer?
Add Answer to:
why should we program for exceptions? Using code snippets, provide an example situation where programming for...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT