1z0-809 Oracle Java SE 8 Programmer II – Exceptions and Assertions
January 27, 2023

1. 6.1 Use try-catch and throw statements

Hello everyone. In this lesson, we will focus on the first item of the exceptions and assertions topic in the Java Se Eight Programmer Two exam syllabus that is using try, catch and throw statements. The try block is the first step in constructing an exception handler. In closing statements that might throw exceptions, a try block must be followed by a catch or finally block. Here is the syntax of a try block starting with the try keyword, then a block of code that might throw exceptions. A try block must be followed by a catch or finally block. The catch block will be introduced now, while the finally block is covered in the next lesson. The catch block is the main component of an exception handler containing code handling exceptions of the type specified by its parameter. A catch block is used to process exceptions thrown from the preceding try block. Here is the syntax of a catch block. The block must follow a triblock or other catch blocks that follow a triblock.

The first component of a catch block is the catch keyword. Next comes the declaration of an exception parameter whose type is a subclass of the throwable class. The last component of the catch block is a block of code that gets executed when an exception whose type is assignable to the type of the exception parameter is thrown from the associated triblock. This exception parameter can be referred to from the block body. The throw statement is used to throw an exception. It requires a single argument a throwable instance.

Throwable instances are instances of any class that extends the throwable class. This is the syntax of the throw statement. It is pretty simple. Starting with the throw keyword, then a throwable object. A throw statement is often wrapped in a try or a catch block. Let’s see how a try and catch block work together. If you write a try block that stands alone like this, you will end up with a syntax error. The error disappears if you add a catch block. Notice that the exception type over here must be a subclass of throwable. Otherwise the compilation fails. A statement that could throw an exception like this should be enclosed in a try block. This division operation is invalid, resulting in an arithmetic exception. That exception’s type is a subclass of runtime exception, so it will be caught by this block. Let’s handle the exception by simply printing the stack trace on the console. You can see that the try catch statement works as expected.

An exception is thrown over here, then caught and handled here in the catch block. A throw statement can be used inside of a try block like before, a stack trace is printed from the catch block. Also, rather than using the catch block to completely handle an exception, you can throw an exception up the call stack from within it. This time, a stack trace is printed by the default exception handler. Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time. In a Try Catch statement, no code can be inserted between the end of the try block and the beginning of the catch block like this. As a result, a compilation error occurs and the correct answer is D. Now for the second question.

A catch block can only handle an exception from a try block if the type of its parameter is the same as, or a supertype of the type of that exception. This requirement is not met in the given scenario, where a catch block with the exception parameter type runtime exception cannot catch an instance of the exception class. Since the throne exception is not caught, this code fragment throws an exception and the correct answer is B. In this lesson, we have gone over how to use the Try, Catch, and throw statements. In summary, the try block is the first step in constructing an exception handler. In closing statements that might throw exceptions, a try block must be followed by a catch or finally, block. The catch block is the main component of an exception handler containing code handling exceptions of the type specified by its parameter. A catch block is used to process exceptions thrown from the preceding triblock. The throw statement is used to throw an exception. It requires a single argument a throwable instance.

2. 6.2 Use catch, multi-catch, and finally clauses

Hello everyone. In this lesson we will go over the second item of the exceptions and assertions topic and the Java Se eight programmer two exam syllabus that is using catch, multipath and finally clauses in a Try Catch statement. Multiple catch blocks can be specified like this. These blocks must be placed next to each other with nothing in between. A catch block is invoked if it is the first one whose parameter type is the same as or a super type of the throne exceptions type. In this case, all of the following catch blocks are ignored. If two or more catch blocks have parameter types in the same class hierarchy, they must be ordered from the most specific to the most general. This means that a catch block cannot be placed before another one if its parameter type is a superclass of the parameter type of the other block. This requirement is to avoid unreachable code, because if an exception could be handled in a more specific catch block, it would have always been caught in a more general one. As of Javas Seven, a catch block can handle more than one type of exception, allowing for more concise exception handling code. Those exception types are separated by the pipe character.

The exception parameter is specified after exception types. In a multi catch block, all exception parameter types must be unrelated. In other words, those types must not be a superclass and subclass of each other. This restriction is imposed to avoid redundant code, since if an exception were caught by a more specific type, it could always be by a more general one. The exception parameter of a multi catch block is implicitly final. You cannot assign any values to it inside of the catch block. An exception handler can have zero or one finally block. If such a block is declared, it must be the last component of the handler. Like other blocks of an exception handler, the syntax of the Finally Block is simple. With the finally keyword and a body, a Finally Block is always executed when the preceding Try block exits, no matter whether an exception is thrown. Due to this feature, the finally block is usually used to implement the final handling of exceptions or to clean up resources. Notice that if a fatal issue occurs, such as the Java virtual machine exits, or the thread in which the Try or Catch block runs is interrupted or killed, the finally block may not be executed.

Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time. When multiple catch blocks are specified in an exception handler, a more general block must not be placed before a more specific one. The block order in this scenario makes the second catch block unreachable, resulting in a compilation error, so the correct answer is D. Now for the second question. When multiple exception types are specified in a catch block, the exception parameter is implicitly final, meaning that it cannot be reassigned like this. As a result, this code fragment fails to be compiled and the correct answer is D. Now for the third question. In this situation, an exception is thrown from the catch block, so the given code fragment ends with an exception being thrown. However, due to the existence of a finally block, that exception throwing is put on hold until the finally block finishes its execution.

So the correct answer is C. In this lesson, we have gone over multicatch and finally blocks in a Try catch statement. To summarize, multiple catch blocks can be declared in a Try catch statement ordered from the most specific to the most general. A multicatch block can handle more than one type of exception. In such a block, all exception parameter types must be unrelated and the exception parameter is implicitly final. An exception handler can have zero or one finally blocks, which is always executed when the try block exits. If a finally block is specified, it must be the last component of the exception handler.

3. 6.3 Use Autoclose resources with a try-with-resources statement

Hello everyone. In this lesson, we will go over the third item of the exceptions and assertions topic and the Java Se Eight programmer two exam syllabus that is using autoclose resources with a Try with Resources statement. The Try with Resources Statement works with resources, so before going deeper into this kind of statement, you should understand what resources are. A resource is basically an object that must be closed after the program is finished with it. All objects whose class implements the auto closable interface, which includes objects whose class implements closable, can be used as resources. The Try with Resources statement is a try statement that declares one or more resources. The difference between the Try block of this statement and one of an ordinary Try Catch statement is the Declaration of resources enclosed within a pair of parentheses and separated by the semicolon character. It is required that all resources declared in a Try with Resources Statement are instances of classes which implement the auto closable interface.

The close method specified in that interface is invoked when a resource is closed. Unlike an ordinary Try Catch statement, the Try block in a Try with Resources statement does not need to be followed by a Catch or Finally Block. However, it is totally valid to complete a Try with Resources statement with such a block. All resources declared in a Try with Resources statement are closed when the Try block exits, regardless of whether it finishes normally or throws an exception. Resources declared in a Try with Resources statement are closed in the opposite order of their creation.

In a Try with Resources statement, catch and Finally Blocks, if any, are executed after the declared resources are closed. A Try with Resources statement has similar functionality to an ordinary Try Catch Statement ending with a Finally Block which contains code that closes the declared resources. The main difference between these two statements lies in the way exceptions are handled in a Try with Resources statement. If exceptions are thrown from both the Try Block and during the closing of Resources, the statement then throws the exception from the triblock, while the exception caused by resource closing is suppressed.

On the contrary, in a Try Catch Statement, if exceptions are thrown from both the triblock and during the closing of resources in the Finally Block, the statement then throws the exception from the Finally Block, while the exception from the tribe block is suppressed. The difference in exception handling in these cases might be confusing, but if you take a deeper look at the reason behind each block’s existence, things should be clear. In an ordinary Try Catch Statement, the Finally Block is used for the final handling of exceptions, so if it throws an exception, such an exception should be the final result of the statement. On the other hand, in a Try with Resources Statement, resources are implicitly closed. An exception thrown from an implicit operation is less important than one from an explicit operation. Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time.

It is valid to have more than one resource and a Try with Resources statement. You just need to separate them using the semicolon character. Also, that statement is not required to have a catch or finally block like an ordinary Try Catch statement. Therefore, option A and option C are incorrect. The resources specified and a Try with Resources statement must be declared inside the statement, not outside of it like this. So the correct answer is B.

As a side note, in Java Nine, a resource can be declared before being used in a Try with Resources statement. However, such a declaration is forbidden in Java Eight. Now for the second question when a resource is declared in a Try with Resources Statement, it is always closed, no matter whether the try block exits normally or abruptly due to an exception. So despite this exception, both of these resources are closed and closed in the opposite order of their creation. Therefore, file reader two is closed before file reader One, and the correct answer is B. Now for the third question if exceptions occur during the closing of a resource and in the tribe block as well, the exception caused by resource closing is suppressed, whereas the exception originated in the triblock is thrown.

As a result, this statement throws a runtime exception which is caught by this catch block and printed on the console over here. So the correct answer is B. In this lesson, we have gone over autoclosable resources and the Try with Resources Statement. To sum up, the Try with Resources statement is a try statement that declares one or more resources. These resources must be instances of classes that implement the autoclosable interface. All resources declared in a Try with Resources statement are closed when the try block exits, regardless of whether it finishes normally or throws an exception in a Try with Resources statement. If exceptions are thrown from both the triblock and during the closing of resources, the statement then throws the exception from the triblock, while the exception caused by resource closing is suppressed.

4. 6.4 Create custom exceptions and Auto-closeable resources

Hello everyone. In this lesson, we will go over the fourth item of the Exceptions and Assertions topic and the Java Se eight programmer two exam syllabus that is creating custom exceptions and autoclosable resources. To create a custom exception, you just need to extend the Java Laying Exception class. This class has five constructors that can be invoked from constructors of the custom exception class. You can find more details about those constructors in the Java API. Documentation. Our custom class over here defines only one constructor to create exception objects with a detailed message. An instance of a class that directly extends the Java Laying Exception class is Checked exception. Therefore, if such an exception is thrown, it must be caught right away or specified in the Throws clause of the enclosing method. If you throw a checked exception and neither catch nor specify it in the Throws clause, a compilation error will occur. Instead of declaring a checked exception class, you can define an unchecked exception class by extending the Runtime exception type, which is a subtype of Java lang exception.

An unchecked exception does not require to be caught nor specified, so a code fragment like this works fine even when an exception of type my exception is not handled. To create a custom resource, you must define a class that implements the Autoclosable interface. This interface represents an object that may hold resources until it is closed. The Autoclosable interface defines a method closing the resource on which it is invoked and relinquishing any underlying resources. You can also implement the Closeable interface, which is a sub interface of auto closable. To create a resource, the closeable interface embodies a source or destination of data that can be closed. It declares a method closing the stream on which it is called and releasing any associated system resources. Notice that the close method of Autoclosable throws an exception, whereas the close method of Closable throws an IO exception. This means that you cannot declare a custom resource class which implements the closeable interface with the Close method. Specifying a checked exception that is not IO exception or one of its subtypes. Here is the declaration of a resource class that implements the Autoclosable interface. It’s two methods open and Close just print messages on the console. Since my resource is an Autoclosable implementation, it can be instantiated in a Try with Resources statement. After the resource is opened, it is automatically closed. This code fragment prints two strings when it is executed. In this example, our custom resource class implements the closeable interface, so it can also be used in a Try with Resources statement.

The close method over here is declared with IO Exception. Notice that you can only specify IO Exception or one of its subclasses on this method, or do not indicate any exception at all. Since the Close method specifies a checked exception, such an exception should be handled over here. After execution, this code fragment prints these two messages. Let’s see how a custom resource and custom exception work with the Try with Resources Statement. First, there is a resource class named Myresource. This class implements the Autoclosable interface, so it must provide an implementation for the close method. An instance of the Myresource class is created here in a Try with Resources Statement. We leave this try block empty when it finishes execution.

The close method on that resource is invoked to release the memory it occupies. You can see a string printed over here which is output from the close method in our custom resource class. Now we have a custom exception class. The close method in My resource now throws an instance of My exception. Myexception is a checked exception, so we need to specify it in the enclosing method. To solve this error, we declare a catch block. The message inside the caught exception is then printed on the console. Run the program. You can see an exception message is output. If the try block throws an exception, such an exception will be thrown while the exception caused by the closed method is suppressed, as shown here. You might retrieve the suppressed exception.

This way, the exception message resulting from resource closing appears again. Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time. My exception is a checked exception because it extends another checked exception. When a checked exception is thrown, it must be caught or specified in the throws clause of the enclosing method. This requirement is not satisfied over here, so the main app class fails to be compiled and the correct answer is A. Now for the second question. When a resource class implements the closeable interface, its close method cannot specify any checked exception other than the IO exception and its subtypes. The given declaration violates that constraint. As a result, a compilation error occurs and the correct answer is D. In this lesson, we have gone over how to create custom exceptions and autoclosable resources. In short, a custom exception can be created by extending the exception class. A custom resource can be created by implementing the Autoclosable interface.

5. 6.5 Test invariants by using assertions

Hello everyone. In this lesson, we will cover the last item of the exceptions and Assertions topic and the Java Se Eight programmer two exam syllabus that is testing invariance by using Assertions before going into the Assertions Statement, you should understand what invariants are first. In computer science, invariants are basically conditions that hold true during the execution of a program. Don’t worry if this definition sounds too vague to you. The examples that follow should make it clear. Assertions are statements that enable you to test your assumptions about the program, allowing for effectively detecting and fixing bugs. An assertion has a boolean valued expression, also called predicate you believe will evaluate to True. When executed, such an assertion statement throws an Assertion error if the given predicate is false.

The Assertion statement has two forms. The first form starts with the assert Keyword and ends with a predicate that should evaluate to True. If this expression evaluates to False, the assertion throws an Assertion Error with no detail message like the first form. The second form begins with the assert keyword, then a predicate followed by the colon token. This assertion form completes with an expression that evaluates to a value. If an Assertion Error is thrown, the textual representation of that value is used as the detail message of the error. Notice that the purpose of such a detailed message is to communicate the details of the assertion failure. It is not meant to inform end users and just needs to be understandable in the context of a full stack trace. Therefore, the message can be very concise. Assertions can be used for internal invariance that validate the value of local variables. Here is a code fragment demonstrating internal invariance using assertions. This if branch is executed if variable I is an odd number. Therefore, in this else branch, you can rest assured that I is an even number and the assertion should not fail.

 An assertion can be placed at any location you assume will not be reached. This kind of invariant guarantees that the preceding code works as expected. Notice that the place you put the assertion at should be unreachable due to data correctness. It must not be the result of a language structure, such as when you have a statement right after an explicit exception. Throwing that kind of unreachability leads to compilation errors instead. In this example, the gender enum type contains these three constants. You may assume that no objects of this enum will have this value, so this gender variable must match one of these cases.

The default branch over here should never be reached, so you can place an assertion here. If the invariant is violated, a message which is the string representation of the invalid gender value is included in the throne error. There are two kinds of condition invariance precondition and post condition precondition and variance specify what must be true when a method is invoked while post condition invariance, as you might have guessed, do the same thing when a method completes. In the method over here, this assertion contains a precondition invariant verifying that the operant of a square root operation is nonnegative. The post condition insertion here confirms that the result of such an operation is also nonnegative. Note that a postcondition invariant serves to validate the operation of a method so it can be used in any method. But a precondition invariant should not be used in a public method which is directly called by a client. In fact, a precondition invariant is more suitable for something like a helper method that is invoked by another method. The reason is that assertions might be disabled at Runtime. If you use them for critical operations such as checks on users input data, you may end up with no checks at all, which may turn into a disaster. Class invariants are invariants used to constrain the state stored in objects of a class. These invariants are established during object construction and preserved by public methods. Here is a class declaration that illustrates class invariance. This is a method ensuring that the date and month values are valid. This method can be used as part of an assertion when an object is created, as well as in a public method right before it’s return. In Java, eight assertions are compiled by default, so you do not need to specify any options when compiling source files. On the other hand, assertions are disabled at Runtime by default, so you must use the flag Enable Assertions or EA for short to enable them when starting a program. Assertion statements are very useful in testing. However, there are some situations you should avoid using them. Assertions should not be used for critical checks.

The reason is that those checks should be in place regardless of whether assertions are enabled or not. In addition, assertions force you to throw assertion errors in case of failure rather than appropriate exceptions. An example of such checks is the validation of users input. Assertions should be free of side effects. The expression contained in an assertion should not modify any object state after its execution is completed. An exception to this constraint is that assertions can modify state which is only used by other assertions. Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time. This program runs with assertions enabled at Runtime.

This expression evaluates to true so the assertion over here is executed, resulting in an assertion error. At this point, the program terminates and this statement is ignored, so the correct answer is B. Now for the second question. In a given scenario, if this expression evaluates to true, the method returns the operation result. Otherwise, an error is thrown. Consequently, this assertion statement can never be reached regardless of the argument value. This unreachability results in a compilation error, so the correct answer is D. In this lesson we have gone over testing invariance using the assertion statement. In summary, an assertion statement throws an assertion error if the given predicate evaluates to false by default. Assertions are accepted during compilation but disabled at runtime. You can enable assertions when running a program using the flag enable Assertions or EA for short.

Leave a Reply

How It Works

img
Step 1. Choose Exam
on ExamLabs
Download IT Exams Questions & Answers
img
Step 2. Open Exam with
Avanset Exam Simulator
Press here to download VCE Exam Simulator that simulates real exam environment
img
Step 3. Study
& Pass
IT Exams Anywhere, Anytime!