Need of Java's "more precise rethrow in exceptions"

importance of java
importance of java in today's world
what is java used for
java vs python
what is java programming used for
advantages of java
features of java
java download

I am having trouble understanding how precise rethrow works in Java 7 and later versions. As pointed out in https://www.theserverside.com/tutorial/OCPJP-Use-more-precise-rethrow-in-exceptions-Objective-Java-7, in Java 7 and later versions we can use the throws clause, in a method declaration, with a comma-separated list of specific exceptions that the method could throw. If all these exceptions are subtypes of the general exception java.lang.Exception, we will be able to catch any of them in a catch block that catches this supertype, while letting client code (eg. a caller method) to know which of the possible subtypes exceptions actually occurred.

Initially, I thought that in order to let know client code which exception actually occurred, we needed to specify the list of specific exceptions in the throws clause. Nevertheless, in the following example the client code (the main() method) seems able to retrieve that information, even if we only specify the exception java.lang.Exception in the throws clause of the called method. Therefore, my question is:

Why the following code outputs the same, regardless of whether the throws clause of the method runException() is throws ExceptionA, ExceptionB or throws Exception ?

I am using Oracle JVM-12 in Eclipse. Thanks in advance!

class ExceptionA extends Exception{}
class ExceptionB extends Exception{}

public class RethrowingAndTypeChecking{
    public static void runException(char what) throws Exception{
    //public static void runException(char what) throws ExceptionA, ExceptionB{
        try{
            if(what == 'A') 
                throw new ExceptionA();
            else if (what == 'B')
                throw new ExceptionB();
        }
        catch(Exception e){
            throw e;
        }
    }

    public static void main (String args[]){
        char ch;
        for (int i=0;i<2;i++) {
            if(i==0) ch='A';
            else ch = 'B';

            try{
                runException(ch);
            }
            catch(ExceptionA e){
                System.out.print("In main(), 'catch(ExceptionA e){}', caught exception: " + e.getClass());
            }
            catch(ExceptionB e){
                System.out.print("In main(), 'catch(ExceptionB e){}', caught exception: " + e.getClass());
            }
            catch(Exception e){
                System.out.print("In main(), 'catch(Exception e){}', caught exception: " + e.getClass());
            }               
            System.out.println();
        }
    }
}

output:

In main(), 'catch(ExceptionA e){}', caught exception: class ExceptionA
In main(), 'catch(ExceptionB e){}', caught exception: class ExceptionB

What you're missing is the case where you need to handle those possible exceptions in different ways. Your code is catching individual exceptions, but it is, roughly speaking, performing the same action.

If you were to handle ExceptionA in a considerably different way from how you handle ExceptionB, then catching the broad Exception would not allow you to do that specifically:

catch(Exception e){
    // something unexpected happened
    // e could be an ExceptionA problem
    // e could be an ExceptionB problem
    // e could be any other unchecked exception
}

When the catch(Exception e){} block is entered, the exception could pretty much be anything, but you have only one generic code block to handle it.

Beside this, if the method you're calling declares specific checked exceptions, then the compiler can help you handle only those exceptions, thus adding to the predictability of the code

try{
    runException(ch);
} catch(ExceptionA e){
    // code specific to handling ExceptionA problems
} catch(ExceptionB e){
    // code specific to handling ExceptionB problems

} catch(ExceptionC e){ //will not compile, because not declared by runException
    // code specific to handling ExceptionB problems
}

What is Java and why do I need it?, What is Java technology and why do I need it? Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are� What is Java technology and why do I need it? Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable.

These throws declarations are so that you list more explicitly what happens out of the method. Otherwise this is ordinary polymorphism: you use base class to combine in multiple subclasses, however you are definitely not changing the instances, this is why at runtime in both cases the exceptions are resolved to their concrete classes.

10 Reasons to Learn Java Programming Language , Since Java is free from the start, i.e., you don't need to pay anything to create Java application. This FREE thing also helped Java to become� Java allows you to play online games, chat with people around the world, calculate your mortgage interest, and view images in 3D, just to name a few. Java software for your computer, or the Java Runtime Environment, is also referred to as the Java Runtime, Runtime Environment, Runtime, JRE, Java Virtual Machine, Virtual Machine, Java VM, JVM

As a rule, you should never catch (Exception ex). Because this will catch RuntimeExceptions too. It sometimes makes sense to catch (Throwable t) or to use Thread.setDefaultUncaughtExceptionHandler to customize your uncaught exception handler to catch exceptions and then display them to the user. Sometimes I will catch an Exception, wrap it in a RuntimeException (or an Error) and throw that

When it comes to exceptions, you should really only be catching them when you can do something with them, or when you want to make sure that an exception doesn't cause the rest of the method to not process.

Personally I divide exceptions into 3 types

  1. Problems in your code: This is something for you to fix
  2. Problems with the user: For instance if you tell them to enter a number and they enter 'a', that's the user's error
  3. "Friend" Exceptions: SocketException, for instance, is an example of this. If the socket closes and you have a thread waiting on input on it, it will throw this Exception, releasing the thread and letting you do clean-up on the socket.

5 Reasons Why You Need to Learn Java Programming, 5 Reasons Why You Need to Learn Java Programming. 01/16/2017. woman on laptop learning about Java programming If programmers run the world, then� Most often Java is used to build large enterprise class applications. Java works great within corporate environments, or if you’re building a very large scale system. Although it can be used for small tasks, it’s less suited for that. In Dev Ops, where you need to create quick scripts, Java might be a little too heavyweight.

Quoting @Carlos Heuberger, my code outputs the same, regardless of whether the throws clause of the method runException() is throws ExceptionA, ExceptionB or throws Exception because:

the run-time type of the exception is used to select the catch clause: see 14.20.1. Execution of try - catch

Whatever the exception reference type (in this case ExceptionA, ExceptionB or Exception) used to refer to the exception object thrown by method runException(), such method will throw objects of type either ExceptionA or ExceptionB. These objects will be assignment compatible with the catch parameters of the first two catch of the main() method.

After paragraphs 8.4.6, 11.2.3 and 14.20.1 of the Java Language Specification, I understood that what we actually specify in a throws clause of a method signature is the list of the exception reference types that will be assignment compatible with any possible exception object thrown from the method (given a class reference type we can make it point to instance objects of itself or to instance objects of its subclasses, not superclasses ). That tells any other caller method what exceptions it may have to deal with when invoking the method with the throws clause. In my code example, the advantage of using the clause throws ExceptionA, ExceptionB is that I will not need to catch java.lang.Exception in the main(). In fact, if I choose clause throws Exception in method runException() and delete the cath(Exception) block from the main() I will get a compile-time error. This is because even if we will be throwing ExceptionA or ExceptionB objects at run-time, the compiler will understand that method runException() may throw out an exception object of type Exception, which will not be assignment compatible with any of the catch parameters in the main() (Exception is a superclass of both ExceptionA and ExceptionB).

What is Java and why is it important?, 'Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network. It can also be used� Java is high level programming language and it is best than others languages. Java contains some features of c++ and some syntax of c. Java is called as pure object oriented programmimg language because all code based on the classes and object, even main () is also included in class.Java is very popular language for web development.

Where is Java used?, Since Java is a Turing-complete language--one that is extraordinarily well- designed from a software Originally Answered: What is the need for Java? Java is� Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

Java: Everything a Beginner Needs to Know, Java: What Beginners Need to Know Now. By: David WintrichNovember 16, 2017 . Java code programming computer. back� Java Object Oriented Programming Programming A Wrapper class is a class which contains the primitive data types ( int, char, short, byte, etc) . In other words, wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects .

What is Java and can I do without it? - May 2016 - Forums, If you are not running any JAVA applications, then you don't need JAVA on your machine. In the early days of JAVA, the installation of applications automatically� Perhaps the easiest way to tell whether or not you need Java is to first disable it entirely. If you regularly use an application or visit a Web site that requires Java, your system or the site

Comments
  • I don't think I understand your question. The catch that is the most specific is going to be the one that is executed.
  • quick answer: the run-time type of the exception is used to select the catch clause: see 14.20.1. Execution of try - catch
  • @CarlosHeuberger, Do you mean that the catch block that is executed in the main() is the first-found which defines in its parameter an exception reference type that can point to the reference object being thrown from method runException() ? That can be an answer to my question, because the method runException() will always throw objects of either type ExceptionA or ExceptionB, regardless of the reference type used to point to them (i.e. java.lang.Exception or ExceptionA or ExceptionB).
  • yes, or see specification: "if the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected." - important is the run-time type, not the type specified in throws declaration
  • @CarlosHeuberger, I think I got it. Thanks for addressing me to paragraph 14.20.1 of the Java Specification. In addition to that paragraph I cleared my doubts after paragraphs 8.4.6 and 11.2.3. Could you please post your comments as an answer so I can accept it as the one solving my problem ?
  • The exception could be pretty much anything as you say, but inside the main() I am able to spot exactly which one occurred, as can be seen from the different strings printed. Therefore, it seems to me that I still could potentially handle those possible exceptions in different ways, as you say. Could you show me an example in which a code similar to mine wouldn’t be able to spot which exception occurred (and therefore couldn’t handle it properly) ? or may be an example illustrating the limitations of the way in which I spot the exception?
  • @gambarimas87 It's not because the more general exception would make it impossible to handle specific errors, it's rather because that becomes messy very quickly. The intent of the exception hierarchy is to have handling code based on the exception type alone. That's why Java compiler and runtime are very systematic about exception blocks. In your case, for example, you would have to read the exception object's message property to decide what action to perform... of course you can do that, but the language allows you to design better based on exception types only.