0

What is the use of try and catch keywords in c++?

I came across these keywords in my turbo c++ compiler and I have absolutely no idea about their function.

21st Nov 2016, 9:01 AM
Chitransh Vishwakarma
Chitransh Vishwakarma - avatar
9 Respostas
0
Its a way of avoiding errors in your code lets say you want to divide a number by zero, i the real word a division by zero has no meaning but you computer doesn't know that so it will do the task and your program will fail. If you introduce the try catch the program will try to divide by zero if it fails the catch clause will be executed thus your program will not fail
21st Nov 2016, 9:18 AM
Agaba Ivan
Agaba Ivan - avatar
0
but how will the compiler know that the program has failed !
21st Nov 2016, 9:22 AM
Chitransh Vishwakarma
Chitransh Vishwakarma - avatar
0
The compiler will not know that the program has failed until it fails to compile the program, thus it's the job of the programmer to ensure that the program is written well
21st Nov 2016, 9:28 AM
Agaba Ivan
Agaba Ivan - avatar
0
I want u to write a divide by zero program without the try catch run it and see what happens
21st Nov 2016, 9:29 AM
Agaba Ivan
Agaba Ivan - avatar
0
will you please give an example of using those two keywords for diving any number by zero. Thanks
21st Nov 2016, 9:33 AM
Chitransh Vishwakarma
Chitransh Vishwakarma - avatar
0
//This is a sample program written in Java to illustrate divison by zero public class Program { public static void main(String[] args) { int x =100; int y=0; double z=x/y; System.out.println (x/y); } }
21st Nov 2016, 9:41 AM
Agaba Ivan
Agaba Ivan - avatar
0
and this is a sample program written in c++ to illustrate division by zero int main() { int a=2,b=0; return a/b; } (-_-) I need a sample program written in C++ illustrating the use of "try" and "catch" keywords.
21st Nov 2016, 9:46 AM
Chitransh Vishwakarma
Chitransh Vishwakarma - avatar
0
I may have to learn some of the syntax in C++ to know how to do that one the java version would be like this public class DivideZero { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int x = 100; int y = 0; try{ System.out.println(x / y); } catch(ArithmeticException e){ System.out.println(e.getMessage());} } }
21st Nov 2016, 11:18 AM
Agaba Ivan
Agaba Ivan - avatar
0
Thanks
21st Nov 2016, 12:46 PM
Chitransh Vishwakarma
Chitransh Vishwakarma - avatar