Please anyone give me the idea how can we catch multiple exceptions with a single catch block ???
Multiple Exceptions ???
Resolved
Comments (14)
- Popular
- New
- Old
You must be signed in to leave a comment
MaGaby2280
1 November 2019, 18:51
Took me a while... it mught help someone:
public static void handleExceptions(Solution obj) {
try {
obj.method1();
obj.method2();
obj.method3();
} catch (IOException e) {
System.out.println(e);
} catch (NoSuchFieldException e) {
System.out.println(e);
}
}
0
Ashish Methani
27 April 2019, 07:17
try{
obj.method1();
obj.method2();
obj.method3();
}
catch(Exception e){System.out.println(e);}
+5
Ronnie Stephens
15 May 2019, 20:39
Thanks!
confusing task to me.
0
Sergei Polakov
3 June 2019, 15:20
great!
0
sathya
2 March 2019, 16:17useful
int i = 1;
while(i <= 3)
{
try{
if (i == 1)
obj.method1();
else if (i == 2)
obj.method2();
else if (i == 3)
obj.method3();
}
catch(Exception ex)
{
System.out.println(ex);
}
i++;
}
+19
Oleg Vanyushkin
9 April 2019, 19:48
Brilliant!
0
nikhil singla
7 September 2019, 06:13
best solution !!
0
Kavita Rao
8 October 2019, 20:55
Thank you. I just could not figure out how to display all three exceptions.
0
Sela
6 July 2020, 05:48
this is the solution that strictly fulfills the fifth requirement to "...should catch and display all the exceptions that occur.". but the code that displays only one of the exceptions passes the validation. maybe this is because of the word "...should..." meaning not have to. also give a like.
0
Hashirama
26 January 2019, 12:58
Only the first line of code in the try block will be caught. The rest won't be because, once an exception occurs, the rest of the code won't execute and it jumps straight to the catch block.
So you should use Exception e.
That way any exception that occurs will be caught.
Also, don't forget to display the type of exception that gets caught.
+1
Khurram
22 October 2018, 18:07
you could use catch (Exception e), because all exceptions inherit Exception
0
Varma7590
23 October 2018, 12:57
Yeah , but once an exception is caught from try block we can't actually return to try block again to try the second method like
try
{
method1();
method2();
method3();
}
catch................
Here the catch catches only the first method's exception but how can we again do this with method2() and method3()......And the condition is like we must use only one try-catch block.???
0
Ivaylo Trifonov
27 March 2019, 16:17solution
@Varma7590, observe the code example provided by @sathya.
+1
Darko Jakimovski
16 April 2019, 15:33
The catch statement is also in the while loop so it will go through all of the method calls.
+1