0% found this document useful (0 votes)
6 views

5 - Java Exception Handling

Uploaded by

Nguyen Huy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

5 - Java Exception Handling

Uploaded by

Nguyen Huy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Java Basic for Tester

Java Exceptions

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1


Agenda

 Java Exceptions
 Java Exception Handling
 Java throw and throws
 Java catch Multiple Exceptions
 Java try-with-resources
 Java Annotations
 Java Annotation Types
 Java Logging
 Java Assertions
1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2
Java Exceptions

An exception is an unexpected event that occurs during program


execution. It affects the flow of the program instructions which can cause
the program to terminate abnormally.

Invalid user input

Device failure

Loss of network connection


Many reasons
Physical limitations (out of disk memory)

Code errors

Opening an unavailable file

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 3


Java Exceptions

Java Exception hierarchy

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory,
memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.

Exceptions can be caught and handled by the program. When an exception occurs within a method,
it creates an object. This object is called the exception object.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 4


Java Exceptions

Java Exception
Types

RuntimeException IOException

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5


Java Exceptions

A runtime exception happens due to a programming error. They are also


known as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of the
common runtime exceptions are:

 Improper use of an API - IllegalArgumentException


 Null pointer access (missing the initialization of a variable) -
NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 - ArithmeticException

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


Java Exceptions

An IOException is also known as a checked exception. They are checked


by the compiler at the compile-time and the programmer is prompted to
handle these exceptions.

Some of the examples of checked exceptions are:


 Trying to open a file that doesn’t exist results in FileNotFoundException
 Trying to read past the end of a file

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7


Java Exception Handling

Catching and handling exceptions


In Java, we use the exception handler components try, catch and finally
blocks to handle exceptions.
To catch and handle an exception, we place the try...catch...finally block
around the code that might generate an exception. The finally block is
optional.
try {
// code
} catch (ExceptionType e) {
// catch block
} finally {
// finally block
}
1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8
Java Exception Handling

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9


Java Exception Handling

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10


Java Exception Handling

Catching Multiple Exceptions


From Java SE 7 and later, we can now catch more than one type of exception with
one catch block.
This reduces code duplication and increases code simplicity and efficiency.

try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


Java throw and throws

In Java, exceptions can be categorized into two types:

1. Unchecked Exceptions: They are not checked at compile-time but at


run-time.For example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, exceptions under Error class, etc.

2. Checked Exceptions: They are checked at compile-time. For example,


IOException, InterruptedException, etc.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12


Java throw and throws

Java throws keyword

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


Java catch Multiple Exceptions
Before Java 7, we had to write multiple exception handling codes for different
types of exceptions even if there was code redundancy.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14


Java try-with-resources
The try-with-resources statement automatically closes all the resources at
the end of the statement. A resource is an object to be closed at the end of
the program.

try (resource declaration) {


// use of the resource
} catch (ExceptionType e1) {
// catch block
}

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 15


Java try-with-resources
Declaring and instantiating the BufferedReader inside the try-with-resources
statement ensures that its instance is closed regardless of whether the try statement
completes normally or throws an exception.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 16


Java Annotations
Java annotations are metadata (data about data) for our program source code.

They provide additional information about the program to the compiler but are
not part of the program itself. These annotations do not affect the execution of
the compiled program.
Annotations start with @. Its syntax is: @AnnotationName

@Deprecated
@Override
@SuppressWarnings
@Overload

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 17


Java Annotations

Annotation formats

Marker Single element Multiple element


Annotations Annotations Annotations

@AnnotationName(el @AnnotationName(el
@AnnotationName() ementName = ement1 = "value1",
"elementValue") element2 = "value2")

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18


Java Annotations

Annotation
placement

Above
Type annotations
declarations

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


Java Annotations
Use of Annotations
Compiler instructions - Annotations can be used for giving instructions to
the compiler, detect errors or suppress warnings. The built-in
annotations , , are used for these purposes.

Compile-time instructions - Compile-time instructions provided by these


annotations help the software build tools to generate code, XML files and
many more.

Runtime instructions - Some annotations can be defined to give


instructions to the program at runtime. These annotations are accessed
using Java Reflection.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


Java Annotation Types

• @Deprecated
• @Override
Predefined
• @SuppressWarnings
annotations
• @SafeVarargs
• @FunctionalInterface
• @Retention
• @Documented
Meta-
• @Target
annotations
• @Inherited
• @Repeatable
Custom
• Custom annotations
annotations

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


Java Annotation Types

Predefined Annotation Types


@Deprecated
The @Deprecated annotation is a marker annotation that indicates the element
(class, method, field, etc) is deprecated and has been replaced by a newer element.

@Deprecated
accessModifier returnType deprecatedMethodName() { ... }

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


Java Annotation Types

Predefined Annotation Types


@Override
The @Override annotation specifies that a method of a subclass overrides the
method of the superclass with the same method name, return type, and parameter
list.

@SuppressWarnings
As the name suggests, the @SuppressWarnings annotation instructs the compiler
to suppress warnings that are generated while the program executes.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23


Java Annotation Types

Custom Annotations
It is also possible to create our own custom annotations.

[Access Specifier] @interface<AnnotationName> {


DataType <Method Name>() [default value];
}
1. Annotations can be created by using @interface followed by the annotation name.
2. The annotation can have elements that look like methods but they do not have an
implementation.
3. The default value is optional. The parameters cannot have a null value.
4. The return type of the method can be primitive, enum, string, class name or array of
these types.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


Java Annotation Types

@Retention
The @Retention annotation specifies the level up to which the annotation
will be available.

@Retention(RetentionPolicy)

RetentionPolicy.SOURCE - The annotation is available only at the source level and


is ignored by the compiler.
RetentionPolicy.CLASS - The annotation is available to the compiler at compile-
time, but is ignored by the Java Virtual Machine (JVM).
RetentionPolicy.RUNTIME - The annotation is available to the JVM.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


Java Annotation Types

@Documented
By default, custom annotations are not included in the official Java
documentation. To include our annotation in the Javadoc documentation, we
use the @Documented annotation.

@Documented
public @interface MyCustomAnnotation{ ... }

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


Java Annotation Types
@Target
We can restrict an annotation to be applied to specific targets using the
@Target annotation. Element Type Target
ElementType.ANNOTATION_TYPE Annotation type
ElementType.CONSTRUCTOR Constructors
@Target(ElementType) ElementType.FIELD Fields

ElementType.LOCAL_VARIABLE Local variables

ElementType.METHOD Methods

@Target(ElementType.METHOD) ElementType.PACKAGE Package

public @interface MyCustomAnnotation{ ... ElementType.PARAMETER Parameter


} Any element of
ElementType.TYPE
class

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27


Java Logging
Java allows us to create and capture log messages and files through the
process of logging.

In Java, logging requires frameworks and APIs. Java has a built-in logging
framework in the java.util.logging package.

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28


Java Logging
The Logger class provides methods for logging. We can instantiate objects
from the Logger class and call its methods for logging purposes.
Logger logger = Logger.getLogger(MyClass.class.getName());

logger.info( "This is INFO log level message");


Log Level (in descending order) Use

WARNING warning message, a potential problem

INFO general runtime information

CONFIG configuration information

FINE general developer information (tracing messages)

OFF turn off logging for all levels (capture nothing)

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29


Java Logging
The log handler or the appenders receive the LogRecord and exports it to
various targets.
Handlers Use
writes to an
StreamHandler
//To add a new handler OutputStream
Handler handler = new ConsoleHandler();
ConsoleHandler writes to console
logger.addHandler(handler);
FileHandler writes to file
//To remove a handler
logger.removeHandler(handler); writes to remote TCP
SocketHandler
ports

MemoryHandler writes to memory


//A logger can have multiple handlers
Handler[] handlers = logger.getHandlers();
1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30
Java Logging
A handler can also use a Formatter to format the LogRecord object into a
string before exporting it to external systems.

Formatters Use
SimpleFormatter formats LogRecord to string

XMLFormatter formats LogRecord to XML form

// formats to string form


handler.setFormatter(new SimpleFormatter());

// formats to XML form


handler.setFormatter(new XMLFormatter());

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31


Java Logging

Helps in monitoring the flow of


the program

Advantages Helps in capturing any errors


of Logging that may occur

Provides support for problem


diagnosis and debugging

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32


Thank you

1/5/2022 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33

You might also like