Catch Multiple Exceptions At Once

Catch multiple exceptions at once?

Catch System.Exception and switch on the types

catch (Exception ex)            
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}

throw;
}

Can I catch multiple Java exceptions in the same catch clause?

This has been possible since Java 7. The syntax for a multi-catch block is:

try { 
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
someCode();
}

Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.

Also note that you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, either directly or indirectly, from ExceptionA. The compiler will complain:

Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA

The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.

Can you use multiple catch with same exception

You can't do that. To catch a exception inside a catch block you should user another try/catch.

public function() {
try {
return output;
} catch (Exception e){
try {
return output1;
} catch (Exception e2) {
return output2;
}
}
}

How to catch two or more Exceptions in JAVA?

In Java SE 7 and later, you actually can catch multiple exceptions in the same catch block.

To do it, you write it this way:

         try{
// Your code here
} catch (ExampleException1 | ExampleException2 | ... | ExampleExceptionN e){
// Your handling code here
}

Besides that, you can use an extremely general catching exception like:

try{
// code here
} catch (Exception e){
// exception handling code here
}

But, that is a discouraged practice. ;)

Resources: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html (Oracle Documentation).

Catch Multiple Exception

We can use the isinstance built-in function.

def get(self, request):
try:
payer_data = validate_payer(db=db,request =request,payer = payer,userid = userid)
BODY OF API
except Exception as e:
if isinstance(e,exceptions.NotAcceptable):
raise
elif isinstance(e,exceptions.PermissionDenied):
raise
else:
manager.create_from_exception(e)
return Response(AppResponse.msg(request, 400, 'Something went wrong.', 0, 0, 0), status=status.HTTP_400_BAD_REQUEST)

So if the exception is of class NotAcceptable or PermissionDenied it will raise the exception again otherwise it will give common message Something Went wrong with status code 400

Catching multiple exception types in one catch block


Update:

As of PHP 7.1, this is available.

The syntax is:

try
{
// Some code...
}
catch(AError | BError $e)
{
// Handle exceptions
}
catch(Exception $e)
{
// Handle the general case
}

Docs: https://www.php.net/manual/en/language.exceptions.php#example-294

RFC: https://wiki.php.net/rfc/multiple-catch

Commit: https://github.com/php/php-src/commit/0aed2cc2a440e7be17552cc669d71fdd24d1204a



For PHP before 7.1:

Despite what these other answers say, you can catch AError and BError in the same block (it is somewhat easier if you are the one defining the exceptions). Even given that there are exceptions you want to "fall through", you should still be able to define a hierarchy to match your needs.

abstract class MyExceptions extends Exception {}

abstract class LetterError extends MyExceptions {}

class AError extends LetterError {}

class BError extends LetterError {}

Then:

catch(LetterError $e){
//voodoo
}

As you can see here and here, even the SPL default exceptions have a hierarchy you can leverage. Additionally, as stated in the PHP Manual:

When an exception is thrown, code following the statement will not be
executed, and PHP will attempt to find the first matching catch block.

This means you could also have

class CError extends LetterError {}

which you need to handle differently than AError or BError, so your catch statement would look like this:

catch(CError $e){
//voodoo
}
catch(LetterError $e){
//voodoo
}

If you had the case where there were twenty or more exceptions that legitimately belonged under the same superclass, and you needed to handle five (or whatever large-ish group) of them one way and the rest the other, you can STILL do this.

interface Group1 {}

class AError extends LetterError implements Group1 {}

class BError extends LetterError implements Group1 {}

And then:

catch (Group1 $e) {}

Using OOP when it comes to exceptions is very powerful. Using things like get_class or instanceof are hacks, and should be avoided if possible.

Another solution I would like to add is putting the exception handling functionality in its own method.

You could have

function handleExceptionMethod1(Exception $e)
{
//voodoo
}

function handleExceptionMethod2(Exception $e)
{
//voodoo
}

Assuming there is absolutely no way you can control exception class hierarchies or interfaces (and there almost always will be a way), you can do the following:

try
{
stuff()
}
catch(ExceptionA $e)
{
$this->handleExceptionMethod1($e);
}
catch(ExceptionB $e)
{
$this->handleExceptionMethod1($e);
}
catch(ExceptionC $e)
{
$this->handleExceptionMethod1($e);
}
catch(Exception $e)
{
$this->handleExceptionMethod2($e);
}

In this way, you are still have a only single code location you have to modify if your exception handling mechanism needs to change, and you are working within the general constructs of OOP.

Catch two exceptions in the same catch block?

In fact, you could catch only SystemException and it would handle CommunicationException too, because CommunicationException is derived from SystemException

catch (SystemException se) {
... //this handles both exceptions
}

Catching multiple exceptions in Java-8

The type of the expression

b ? new Excep1() : new Excep2()

is Exception, since that's the common supertype of Excep1 and Excep2.

However, you are not catching Exception, so the compiler complains about it.

If you catch Exception, it will pass compilation:

public int m2(boolean b) {
try {
throw b ? new Excep1() : new Excep2();
} catch (Exception e) {
return 0;
}
}

I tried to find the JLS entry that explains the type of conditional ternary expression in your example.

All I could find was that this particular expression is a 15.25.3. Reference Conditional Expression.

I'm not entirely sure if it counts as a poly expression or a standalone expression. I think it's standalone (since poly expressions involve an assignment context or an invocation context, and I don't think a throw statement counts as either of those).

For a standalone expression: "If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression."

In your case, the second and third operands have three common types - Object, Throwable and Exception - the type of the expression must be one of the latter two, since, "The Expression in a throw statement must either denote a variable or value of a reference type which is assignable (§5.2) to the type Throwable."

It appears that the compiler picks the most specific common type (Exception), and therefore a catch (Exception e) solves the compilation error.

I also tried to replace your two custom exceptions with two sub-classes of IOException, in which case catch (IOException e) solves the compilation error.



Related Topics



Leave a reply



Submit