- 2

Could anyone help in this

b) What are the conditions when exception handling should be used in programs? The following codes contain errors identify those errors and write new codes with exception handling to fix those errors. public class myException { public static void main(String args[]) { int a = 100, b = 0; int result = a/b; System.out.println("Result = " + result); } } B) public class myMain { public static void main(String[] args) { int[] myNumbers = {1, 2, 3, 4, 5}; System.out.println(myNumbers[10]); } }

24th Jan 2021, 8:08 PM
faheem amjad
faheem amjad - avatar
3 Antworten
+ 1
For A you have to throw a ZeroDivision exception and for B you have to throw IndexOutOfBound exception
24th Jan 2021, 9:37 PM
Sattar
Sattar - avatar
+ 1
faheem amjad In Java, there is ArithmeticException. It comes when you divide any number with 0. So in your case you are dividing 100 with 0. When you access data at invalid index then you get ArrayIndexOutOfBoundsException. So in your case you are accessing data at index 10 which doesn't exist in myNumbers array. You can see example here https://code.sololearn.com/c29GGPJ9H0Uv/?ref=app
25th Jan 2021, 9:12 AM
A͢J
A͢J - avatar
- 2
1) change the value of “b” to stop a division by zero error 2) change the 10 in myNumbers[10] to an index within the array (a number between 0-4) public class myException { public static void main(String args[]) { int a = 100, b = 1; int result = a/b; System.out.println("Result = " + result); } } public class myMain { public static void main(String[] args) { int[] myNumbers = {1, 2, 3, 4, 5}; System.out.println(myNumbers[2]); } }
24th Jan 2021, 8:12 PM
Ollie Q
Ollie Q - avatar