5 - Java Exception Handling
5 - Java Exception Handling
Java Exceptions
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
Device failure
Code errors
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.
Java Exception
Types
RuntimeException IOException
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
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
Annotation formats
@AnnotationName(el @AnnotationName(el
@AnnotationName() ementName = ement1 = "value1",
"elementValue") element2 = "value2")
Annotation
placement
Above
Type annotations
declarations
• @Deprecated
• @Override
Predefined
• @SuppressWarnings
annotations
• @SafeVarargs
• @FunctionalInterface
• @Retention
• @Documented
Meta-
• @Target
annotations
• @Inherited
• @Repeatable
Custom
• Custom annotations
annotations
@Deprecated
accessModifier returnType deprecatedMethodName() { ... }
@SuppressWarnings
As the name suggests, the @SuppressWarnings annotation instructs the compiler
to suppress warnings that are generated while the program executes.
Custom Annotations
It is also possible to create our own custom annotations.
@Retention
The @Retention annotation specifies the level up to which the annotation
will be available.
@Retention(RetentionPolicy)
@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{ ... }
ElementType.METHOD Methods
In Java, logging requires frameworks and APIs. Java has a built-in logging
framework in the java.util.logging package.
Formatters Use
SimpleFormatter formats LogRecord to string