What is the use of catch keyword ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

What is the use of catch keyword ?

5th Nov 2016, 1:42 PM
Shruti Singh
Shruti Singh - avatar
8 Answers
+ 4
A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
11th Dec 2017, 10:23 AM
Prabhat Thakur
Prabhat Thakur - avatar
11th Dec 2017, 10:23 AM
Prabhat Thakur
Prabhat Thakur - avatar
+ 3
what kind of exceptions ???
5th Nov 2016, 1:53 PM
Shruti Singh
Shruti Singh - avatar
+ 3
yeah..I want it in c++ I don't know java
5th Nov 2016, 2:05 PM
Shruti Singh
Shruti Singh - avatar
+ 3
thnx kamal
5th Nov 2016, 2:35 PM
Shruti Singh
Shruti Singh - avatar
+ 2
Say suppose you want to build a program for basic division. But what if the user inputs "0" in the denomintor. To handle such a situation exception handling is used. Such situations are called exceptions. main() { int a= 10,b = 0; int c; try{ if(b == 0) throw b; c= a/b; cout<<c; } catch(const int a) { cout<<"exception!! divide by "<<a; } } Here "try" is used to check if denominator is 0. "throw" is used to throw exception if it occurs,else program executes normally. If exception is present, then control moves to the catch block, and s message is displayed that it is divide by zero exception.We call it as "exception caught". I hope it helps.
5th Nov 2016, 2:32 PM
kamal joshi
kamal joshi - avatar
0
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
5th Nov 2016, 1:47 PM
Abdelaziz Abubaker
Abdelaziz Abubaker - avatar
0
try{ Scanenr sc = new Scanner(System.in); int x; System.out.println("Enter a number: "); x = sc.nextInt(); }catch (Exception e){ System.out.println("Enter a Number!"); } /*i f th user Enters a String insted of an Interger then the erro will accure. You can also set it as: catch(Exception e){ System.out.println(e); } /* this will print out the error that has been picked up by the compiler occured during the compiling. Sorry forr duing it in java If you want it in C++ tell me and I will give you an example */
5th Nov 2016, 2:02 PM
Abdelaziz Abubaker
Abdelaziz Abubaker - avatar