Minor Exp 4
Minor Exp 4
Experiment No 4
Aim : To Implement a program in C++ and JAVA to understand Exception handling and Garbage
collection with the syntactic differences between the two languages
Objectives: To understand how exception handling and garbage collection differ in C++ and Java.
Software used : CodeBlocks version 17.12, VSCode 1.47.2 /IntelliJ IDEA 2020.2.3
Problem Statement : To Implement a program in C++ and JAVA to understand Exception handling
and Garbage collection with the syntactic differences between the two languages
Theory:
Only throwable objects can be thrown as objects. All types can be thrown as exception
In java, finally is a block that is executed after try In C++ there is no existence of finally block
catch block for cleaning up.
A new keyword throws is used to list exceptions Throw keyword is used to list exceptions thrown
thrown by a function. by a function.
Both checked and unchecked exceptions are Only unchecked exceptions are present.
present.
1. Exception handling in Java is different because there are no destructors. A finally clause can be
added to force execution of statements that perform necessary cleanup. All exceptions in Java are
inherited from the base class Throwable, so you’re guaranteed a common interface.
myresource mr = b.createResource();
2. Exception specifications in Java are vastly superior to those in C++. Instead of the C++ approach of
calling a function at run-time when the wrong exception is thrown, Java exception specifications are
checked and enforced at compile-time. In addition, overridden methods must conform to the exception
specification of the base-class version of that method: they can throw the specified exceptions, or
exceptions derived from those. This provides much more robust exception-handling code.
3. If the access to a Java handle fails, an exception is thrown. This test doesn’t have to occur right
before the use of a handle; the Java specification just says that the exception must somehow be thrown.
Many C++ runtime systems can also throw exceptions for bad pointers.
4. Generally, Java is more robust, via: – Object handles initialized to null (a keyword)
– Handles are always checked and exceptions are thrown for failures
– All array accesses are checked for bounds violations
– Automatic garbage collection prevents memory leaks
– Clean, relatively fool-proof exception handling
– Simple language support for multi-threading
– Bytecode verification of network applet.
Conclusion- Java Exceptions are great way of handling exceptions. It ensures program integrity in any
condition. As a programmer we should always try to use exceptions as it makes code more reliable.