You are on page 1of 34

Pemrograman Berorientasi

Objek
EXCEPTION HANDLING
Exception Handling
Exception is an abnormal condition.
◦ The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained.
◦ In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
◦ The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.
Exception Handling
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.

An exception can occur for many reasons. Some of them are:


◦ Invalid user input
◦ Device failure
◦ Loss of network connection
◦ Physical limitations (out of disk memory)
◦ Code errors
◦ Opening an unavailable file
Exception
Hierarchy
Exception Handling - 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.

Errors are usually beyond the control of the programmer and we should not try to handle errors.
Exception Handling - Exception
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.
◦ It contains information about the exception such as the name and description of the exception and
state of the program when the exception occurred.
Exception Handling – Types of Exception
Exception Handling –
IO Exception | Checked Exception
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
Exception Handling –
Runtime Exception | Unchecked Exception
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

In a simple term:: “If it is a runtime exception, it is your fault”.


◦ The NullPointerException would not have occurred if you had checked whether the variable was initialized or not before
using it.
◦ An ArrayIndexOutOfBoundsException would not have occurred if you tested the array index against the array bounds.
Java Exception Handling
Exceptions abnormally terminate the execution of a program.

The advantages of Exception Handling in Java:


◦ Provision to Complete Program Execution
◦ Easy Identification of Program Code and Error-Handling Code
◦ Propagation of Errors
◦ Meaningful Error Reporting
◦ Identifying Error Types
Java Exception Handling Keyword
Keyword Description

The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block
try
alone. The try block must be followed by either catch or finally.

The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch
catch
block alone. It can be followed by finally block later.

The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled
finally
or not.

throw The "throw" keyword is used to throw an exception.


The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It
throws
doesn't throw an exception. It is always used with method signature.
Java Exception Handling
Different approaches to handle exceptions in Java::
◦ try...catch block
◦ finally block
◦ throw and throws keyword
Java Exception Handling | try...catch
try {
// code
}
catch(Exception e) {
// code
}

◦ we place the code that might generate an exception inside the try block. Every try block is followed by a
catch block.
◦ When an exception occurs, it is caught by the catch block. The catch block cannot be used without the
try block.
Java Exception Handling | try...catch
class Main {
public static void main(String[] args) {

try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Java Exception Handling | try...catch
class Main {
public static void main(String[] args) {

try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Java Exception Handling | try...catch
Java Exception Handling | finally
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}

◦ In Java, the finally block is always executed no matter whether there is an exception or not.
◦ The finally block is optional. And, for each try block, there can be only one finally block.
◦ If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed
after the try block.
Java Exception Handling | finally
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
Java Exception Handling | finally
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
Java Exception Handling | finally
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 5;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
Java Exception Handling | finally
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 5;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
Java Exception Handling | finally
Java Exception Handling | finally
It is a good practice to use the finally block.
It is because it can include important clean up codes like::
◦ code that might be accidentally skipped by return, continue or break
◦ closing a file or connection
Java Exception Handling |
throw and throws
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to the catch
block.
Java Exception Handling |
throw and throws
public static void validate(int age) {
if(age<18) {
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
Java Exception Handling |
throw and throws
public static void validate(int age) {
if(age<18) {
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
Java Exception Handling |
throw and throws
The throws keyword is used to declare the type of exceptions that might occur within the
method. It is used in the method declaration.
It gives an information to the programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling code so that the normal
flow of the program can be maintained.
Java Exception Handling |
throw and throws
public static void CheckZero(int num) throws ArithmeticException {
int divResult = 10 / num;
}
public static void main(String args[]){
CheckZero(0);
}
Java Exception Handling |
throw and throws
public static void CheckZero(int num) throws ArithmeticException {
int divResult = 10 / num;
}
public static void main(String args[]){
CheckZero(0);
}
Java Exception Handling |
throw and throws
public static void CheckZero(int num) throws ArithmeticException {
int divResult = 10 / num;
}
public static void main(String args[]){
try{
CheckZero(0);
}
catch (ArithmeticException e) {
System.out.println("Error:: input berupa 0");
}
}
Java Exception Handling |
throw and throws
public static void CheckZero(int num) throws ArithmeticException {
int divResult = 10 / num;
}
public static void main(String args[]){
try{
CheckZero(0);
}
catch (ArithmeticException e) {
System.out.println("Error:: input berupa 0");
}
}
Built-in Exception in Java Libraries
◦ ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic operation.
◦ ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
◦ ClassNotFoundException: This Exception is raised when we try to access a class whose definition is not found
◦ FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
◦ IOException: It is thrown when an input-output operation failed or interrupted
◦ InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
◦ NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified
◦ NoSuchMethodException: It is thrown when accessing a method that is not found.
◦ NullPointerException: This exception is raised when referring to the members of a null object. Null represents nothing
◦ NumberFormatException: This exception is raised when a method could not convert a string into a numeric format.
◦ RuntimeException: This represents an exception that occurs during runtime.
◦ StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is either negative or greater
than the size of the string
◦ IllegalArgumentException : This exception will throw the error or error statement when the method receives an argument
which is not accurately fit to the given relation or condition. It comes under the unchecked exception.
◦ IllegalStateException : This exception will throw an error or error message when the method is not accessed for the
particular operation in the application. It comes under the unchecked exception.
Terima Kasih
Tugas
Buatlah contoh pengecekan error / exception handling dalam Java, minimal 2 jenis exception
yang berbeda (selain Arithmetic Exception)!

You might also like