+ 2

Catch and try

what is syntax of try and catch in java and how it works

28th Sep 2018, 3:22 PM
Danna Said
Danna Said - avatar
3 Respostas
+ 4
Try, catch and finally are used in java to catch exception. Any function that throws an exception has to be in a try statement. You have to use it like this: try{ int a = 10/0; } catch (Exception e) { System.out.println( "Error") ; } The stuff in the try block is executed and if it gives an exception the catch block will be executed too. But the catch block ISN'T executed when there is no error. The stuff between () must be an Exception (or it may extend it) You can also catch ArithmeticException for example. You can also put a finally block that is executed whether there is or there isn't an Exception. It syntax is like this: try{ } finally { }
28th Sep 2018, 3:46 PM
Daniele Bonomi
Daniele Bonomi - avatar
0
Java try block is used to enclose the code that might throw an exception and you can only use it within a method. try{ //code that may throw an exception }catch(ExceptionType name){ System.out.println(name);//name will print out the exception } This code will throw an exception because you cant divide by zero, Example: try{ int nums = 10/0; System.out.println(nums); }catch(ArithmeticException ex){ System.out.println(ex); } Output: java.lang.ArithmeticException: / by zero
28th Sep 2018, 4:08 PM
JavaBobbo
JavaBobbo - avatar