Java Interview Guide: How to Build Confidence With a Solid Understanding of Core Java Principles pdfdrive com



Yüklə 0,53 Mb.
Pdf görüntüsü
səhifə14/47
tarix06.05.2023
ölçüsü0,53 Mb.
#108601
1   ...   10   11   12   13   14   15   16   17   ...   47
Java Interview Guide

Try/Catch/Finally
Java provides three keywords that are used to establish an error-handling policy.
The try keyword delineates a block of code that might throw an exception.
The catch keyword designates a handler for a specific type of exception.
An exception that is thrown within a try block will be caught by the first
catch
block whose exception type either matches the thrown exception or is
a superclass of the thrown exception.
The finally keyword delineates a block of code that will be invoked
regardless of whether or not an exception was thrown. A finally block
is generally used to provide cleanup operations. For example, code that attempts
to update a database might be surrounded with a finally block because the
database connection should be closed regardless of whether or not the update
was successful.


Try-With-Resources
Java 7 introduced the try-with-resources statement, which allowed resources that
implement the AutoCloseable interface to be declared as parameters inside
of the try block. When the try block completes, the JVM will automatically
call the close() method on those resources, eliminating the need for
a finally block.


Questions
What is an exception?
What is the difference between an unchecked and a checked exception?
How would you determine whether to use an unchecked or a checked exception?
How does a try/catch/finally block work?
How does the try-with-resources statement work?


Generics
Compile-Time Errors vs Runtime Errors
Compile-time errors are errors that prevent a program from compiling, such as
syntax errors. Runtime errors are errors that occur during the execution of an
application, such as casting an object to an invalid type. Compile-time errors are
easier to fix because the compiler tells you where they occur. Runtime errors are
more difficult to detect and may cause unpredictable behavior in unrelated parts
of the application. It is therefore preferable to catch as many errors as possible
during the compile-time phase.


Generics
Generics were introduced to prevent runtime errors caused by invalid type
casting. For example, it would be legal to add a String to a non-generic List
and retrieve it with a cast to an Integer, resulting
in a ClassCastException. However the same situation with a generic
List
would cause a compile-time error. Without generics, the only
way to accomplish type safety would require a List implementation for every
possible object, such as a StringList, IntegerList, etc.



Yüklə 0,53 Mb.

Dostları ilə paylaş:
1   ...   10   11   12   13   14   15   16   17   ...   47




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©www.azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin