Catch Multiple Custom Exceptions? - C++

c# catch multiple exceptions
multiple catch in c++
catch multiple exceptions java
multiple catch and throw in c++
c++17 exceptions
c++ try catch
exception handling
catching class type exception c++

I'm a student in my first C++ programming class, and I'm working on a project where we have to create multiple custom exception classes, and then in one of our event handlers, use a try/catch block to handle them appropriately.

My question is: How do I catch my multiple custom exceptions in my try/catch block? GetMessage() is a custom method in my exception classes that returns the exception explanation as a std::string. Below I've included all the relevant code from my project.

Thanks for your help!

try/catch block


    // This is in one of my event handlers, newEnd is a wxTextCtrl
try {
    first.ValidateData();
    newEndT = first.ComputeEndTime();
    *newEnd << newEndT;
}
catch (// don't know what do to here) {
    wxMessageBox(_(e.GetMessage()), 
                 _("Something Went Wrong!"),
                 wxOK | wxICON_INFORMATION, this);;
}

ValidateData() Method


void Time::ValidateData()
{
    int startHours, startMins, endHours, endMins;

    startHours = startTime / MINUTES_TO_HOURS;
    startMins = startTime % MINUTES_TO_HOURS;
    endHours = endTime / MINUTES_TO_HOURS;
    endMins = endTime % MINUTES_TO_HOURS;

    if (!(startHours <= HOURS_MAX && startHours >= HOURS_MIN))
        throw new HourOutOfRangeException("Beginning Time Hour Out of Range!");
    if (!(endHours <= HOURS_MAX && endHours >= HOURS_MIN))
        throw new HourOutOfRangeException("Ending Time Hour Out of Range!");
    if (!(startMins <= MINUTE_MAX && startMins >= MINUTE_MIN))
        throw new MinuteOutOfRangeException("Starting Time Minute Out of    Range!");
    if (!(endMins <= MINUTE_MAX && endMins >= MINUTE_MIN))
        throw new MinuteOutOfRangeException("Ending Time Minute Out of Range!");
    if(!(timeDifference <= P_MAX && timeDifference >= P_MIN))
        throw new PercentageOutOfRangeException("Percentage Change Out of Range!");
    if (!(startTime < endTime))
        throw new StartEndException("Start Time Cannot Be Less Than End Time!");
}

Just one of my custom exception classes, the others have the same structure as this one


class HourOutOfRangeException
{
public:
        // param constructor
        // initializes message to passed paramater
        // preconditions - param will be a string
        // postconditions - message will be initialized
        // params a string
        // no return type
        HourOutOfRangeException(string pMessage) : message(pMessage) {}
        // GetMessage is getter for var message
        // params none
        // preconditions - none
        // postconditions - none
        // returns string
        string GetMessage() { return message; }
        // destructor
        ~HourOutOfRangeException() {}
private:
        string message;
};

If you have multiple exception types, and assuming there's a hierarchy of exceptions (and all derived publicly from some subclass of std::exception,) start from the most specific and continue to more general:

try
{
    // throws something
}
catch ( const MostSpecificException& e )
{
    // handle custom exception
}
catch ( const LessSpecificException& e )
{
    // handle custom exception
}
catch ( const std::exception& e )
{
    // standard exceptions
}
catch ( ... )
{
    // everything else
}

On the other hand, if you are interested in just the error message - throw same exception, say std::runtime_error with different messages, and then catch that:

try
{
    // code throws some subclass of std::exception
}
catch ( const std::exception& e )
{
    std::cerr << "ERROR: " << e.what() << std::endl;
}

Also remember - throw by value, catch by [const] reference.

How to Catch multiple exceptions, In the previous tutorial, I have covered how to handle exceptions using try-catch blocks. In this guide, we will see how to handle multiple exceptions and. In the previous tutorial, I have covered how to handle exceptions using try-catch blocks. In this guide, we will see how to handle multiple exceptions and how to write them in a correct order so that user gets a meaningful message for each type of exception. Catching multiple exceptions

Catching Multiple Exception Types and Rethrowing Exceptions with , Rethrowing Exceptions with More Inclusive Type Checking. Handling More Than One Type of Exception. In Java SE 7 and later, a single catch block can handle  The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|). Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final.

Derive all of your exceptions from a common base class BaseException that has a virtual method GetMessage().

Then catch(const BaseException& e).

Catch multiple types of exceptions in one catch block, How to handle multiple types of exception in one catch block? Maybe we could use C#6' Exception Filters Exception Filters. While both of these options work, since C# 6 there is an other way of dealing with this. Since C# 6 we have Exception Filters that allow us to ‘filter’ our catch-blocks. So, for example, if we only want to catch our exceptions when the Logger property on our current object isn’t null, we could write the following:

I had a similar problem today, but it turned out I didn't need my solution to solve my problem. Honestly, I couldn't think of real use cases (logging?), and I didn't find much use for it in my code.

Anyway, this is an approach with type lists (requires C++11). I think the advantage of this approach is that there's no need to have a common base class for custom exceptions (except for std::exception, maybe?). In other words, it is not intrusive to your exception hierarchy.

There might be some subtle errors that I am not aware of.

#include <type_traits>
#include <exception>

/// Helper class to handle multiple specific exception types
/// in cases when inheritance based approach would catch exceptions
/// that are not meant to be caught.
///
/// If the body of exception handling code is the same
/// for several exceptions,
/// these exceptions can be joined into one catch.
///
/// Only message data of the caught exception is provided.
///
/// @tparam T  Exception types.
/// @tparam Ts  At least one more exception type is required.
template <class T, class... Ts>
class MultiCatch;

/// Terminal case that holds the message.
/// ``void`` needs to be given as terminal explicitly.
template <>
class MultiCatch<void> {
 protected:
  explicit MultiCatch(const char* err_msg) : msg(err_msg) {}
  const char* msg;
};

template <class T, class... Ts>
class MultiCatch : public MultiCatch<Ts...> {
  static_assert(std::is_base_of<std::exception, T>::value, "Not an exception");

 public:
  using MultiCatch<Ts...>::MultiCatch;

  /// Implicit conversion from the guest exception.
  MultiCatch(const T& error) : MultiCatch<Ts...>(error.what()) {}  // NOLINT

  /// @returns The message of the original exception.
  const char* what() const noexcept {
    return MultiCatch<void>::msg;
  }
};

/// To avoid explicit ``void`` in the type list.
template <class... Ts>
using OneOf = MultiCatch<Ts..., void>;

/// Contrived example.
void foo() {
  try {
    bar();  // May throw three or more sibling or unrelated exceptions.
  } catch (const OneOf<IOError, OutOfMemory>& err) {
    log() << "External failure: " << err.what();

    throw;  // Throw the original exception.
  }
}

C# Exception Handling Best Practices, NET Exceptions; How to Create Your Own Custom C# Exception Types; How to Find Hidden . Your exception handling code can utilize multiple C# catch why should you care?) up to more advanced and C#-centric ones. Output: Caught exception of demo1 class Caught exception of demo1 class Explanation: The program is similar to previos one but here we have made demo2 as derived class for demo1.Note the catch block for demo1 is written first.As demo1 is base class for demo2 an object thrown of demo2 class will be handled by first catch block.That is why output as shown.

When templates can't, macros save the day. The solution is taken from Boost. It boils to 7 lines of code.

/// @file multicatch.hpp
#include <boost/preprocessor/variadic/to_list.hpp>
#include <boost/preprocessor/list/for_each.hpp>

/// Callers must define CATCH_BODY(err) to handle the error,
/// they can redefine the CATCH itself, but it is not as convenient. 
#define CATCH(R, _, T) \
  catch (T & err) {    \
    CATCH_BODY(err)    \
  }
/// Generates catches for multiple exception types
/// with the same error handling body.
#define MULTICATCH(...) \
  BOOST_PP_LIST_FOR_EACH(CATCH, _, BOOST_PP_VARIADIC_TO_LIST(__VA_ARGS__))
// end of file multicatch.hpp

/// @file app.cc
#include "multicatch.hpp"

// Contrived example.
/// Supply the error handling logic.
#define CATCH_BODY(err)                        \
  log() << "External failure: " << err.what(); \
  throw;

void foo() {
  try {
    bar();  // May throw three or more sibling or unrelated exceptions.
  }
  MULTICATCH(IOError, OutOfMemory)
}

#undef CATCH_BODY

C# - Exception Handling, C# exception handling is built upon four keywords: try, catch, finally, and throw. You can list down multiple catch statements to catch different type of exceptions in case User-defined exception classes are derived from the Exception class. For example if you use a "catch-all" exception as Exception it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all Exception type at the bottom and this will be capture any exceptions

Exceptions - C++ Tutorials, To catch exceptions, a portion of code is placed under exception inspection. Multiple handlers (i.e., catch expressions) can be chained; each one with a different exception types that can be inherited by custom exceptions to report errors:  Whenever we implement multiple catch blocks in C#, then it is not possible to write the catch blocks in the following manner, it raises to compilation error because first catch block Exception can handle all the exceptions. Is it possible to catch all exceptions using a single catch block? Yes, it is possible.

PHP Exception Handling, Basic use of Exceptions; Creating a custom exception handler; Multiple exceptions checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6  C++ custom exceptions for beginners. If something goes wrong in a try catch block, an exception automatically gets thrown. The catch blocks gets the thrown elements. Throws automatically point the runtime to the closest catch block in the stack. Usually you use many throws and a few try / catches.

Multicatch in Java, A Java program to demonstrate that we needed. // multiple catch blocks for multiple exceptions. // prior to Java 7. import java.util.Scanner;. public class Test. You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Throwing Exceptions Exceptions can be thrown anywhere within a code block using throw statement.

Comments
  • Don't throw pointers, omit the new.
  • It's amazing seeing your progression from this point to now, where you're a top SO user with over 40k rep. Truly awesome!
  • @Alex: I'm not sure this is such great advice. In the general case, you don't get to control the definitions of your exceptions (e.g. they're from some library, like Boost).
  • What if I throw an int? or a float? Should I wrap them up in Int or Float class and then derive from them?
  • The code does not work. I didn't pay attention to testing. This is just a wishful thinking. Implicit conversions are not considered in catch.