Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how many except statements can a try-except block have?

+17 votes
asked Jun 16, 2023 by Aishwarya Sulibhavi (220 points)

4 Answers

0 votes
answered Jun 18, 2023 by DEEPADHARSHINI S (140 points)
atleast we should one except block
0 votes
answered Jun 18, 2023 by Peter Minarik (86,240 points)

As many as you want. Start with the most specific first, then the least specific last to catch anything that the previous cases haven't caught yet.

For more details, see here.

+1 vote
answered Jun 21, 2023 by Koyana (160 points)
Infinite, there is no limit for it

But it is encouraged to use a specific number of try - except block, else your code will be super complicated.
0 votes
answered Jul 20, 2023 by Gulshan Negi (1,580 points)

Hello, this is Gulshan Negi

Well, C++ can have multiple catch blocks to handle different types of exceptions. Like Python's try-except block, there is no strict limit to the number of catch statements you can have within a try block in C++.

For example: 

try {
    // Code that might throw an exception
    // ...
} catch (ExceptionType1 &e) {
    // Code to handle ExceptionType1
    // ...
} catch (ExceptionType2 &e) {
    // Code to handle ExceptionType2
    // ...
}
// You can have more catch blocks for other exception types if needed
// ...
catch (ExceptionTypeN &e) {
    // Code to handle ExceptionTypeN
    // ...
}

Thanks  

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...