Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the bitwise OR operator ( | ) used when catching multiple exceptions in Java?

I've just learned that | is used to catch multiple exceptions in the same block; | is the bitwise operator for OR. In this case, is it still used as a bitwise operator or does it have a different meaning when in context?

like image 253
platelminto Avatar asked Sep 07 '15 18:09

platelminto


People also ask

How do you handle multiple exceptions in catch block in Java?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.

How do you handle multiple exceptions in a single catch?

Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block. An old, prior to Java 7 approach to handle multiple exceptions.

Why do we need Bitwise Operators in Java?

Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees.


1 Answers

In this case, is it still used as a bitwise operator or does it have a different meaning when in context?

It has a different meaning - although it's of the same "flavour" in that it's "if exception X is caught, or exception Y is caught, or exception Z" is caught.

In the JLS section 14.20 the | is just included literally in the grammar - it's not the OR operator in this context.

like image 176
Jon Skeet Avatar answered Sep 17 '22 16:09

Jon Skeet