0% found this document useful (0 votes)
0 views7 pages

Exception Handling in Java

Exception Handling in Java is a method for managing unexpected events during program execution, ensuring the application continues to run smoothly. It involves using keywords like try, catch, throw, throws, and finally to handle various types of exceptions, which can be built-in or user-defined. The document also discusses the differences between errors and exceptions, and the advantages of implementing exception handling in Java programming.

Uploaded by

dorayakey.65
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views7 pages

Exception Handling in Java

Exception Handling in Java is a method for managing unexpected events during program execution, ensuring the application continues to run smoothly. It involves using keywords like try, catch, throw, throws, and finally to handle various types of exceptions, which can be built-in or user-defined. The document also discusses the differences between errors and exceptions, and the advantages of implementing exception handling in Java programming.

Uploaded by

dorayakey.65
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Exception Handling in Java

Exception Handling in Java is an effective method for dealing with unwanted


and unexpected events during program execution while maintaining the
application's usual flow. When learning Java, one must be ready to deal with
errors, unexpected inputs, or other exceptions. Java Exception handling is a
technique for handling different types of errors, such
as FileNotFoundExceptions, IOExceptions, ClassNotFoundExceptions,
etc.
In this blog post on Java tutorial, we'll discuss exceptions and their types in
Java, exception handling keywords like try, catch, throw, throws, and
finally, with examples, exception hierarchy, differences between errors
and exceptions, the final, finally, and finalize keywords, etc.

What is an Exception in Java?


Exceptions are unwanted events that disrupt the program's execution. Many
a time, your program looks error-free after writing the code. But, at the time of
execution, some unexpected errors or events or objects come to the surface,
and the program prints an error message and stops executing. Such
unexpected happenings are called exceptions in Java.

Example of Exception in Java

class ExceptionExample {
public static void main(String args[]) {
System.out.println("Welcome to ScholarHat");
int a = 30;
int b = 0;
System.out.println(a / b);
System.out.println("Welcome to the ScholarHat's Java Programming tutorial.");
System.out.println("Enjoy your learning");
}
}
Try it Yourself >>
In the above code, at the 4th line, an integer is divided by 0, which is not
possible, and the JVM(Java Virtual Machine) raises an exception. In this
case, the programmer does not handle the exception, which will halt the
program in between by throwing the exception, and the rest of the lines of
code won't be executed.
Output
Welcome to ScholarHat

Exception in thread "main" java.lang.ArithmeticException: / by zero


at ExceptionExample.main(ExceptionExample.java:6)
There are some specific reasons why exceptions occur in Java:

 User’s Invalid Input


 Database Connection Error
 System Failure
 Network Problem
 Security Compromises
 Errors in Code
 Physical Limitations

What is Exception Handling in Java?


Exception Handling is a way of handling errors that occur during runtime and
compile time. It maintains your program flow despite runtime errors in the
code and, thus, prevents unanticipated crashes. It facilitates troubleshooting
by providing error details, cutting down on development time, and improving
user happiness.

Types of Exceptions in Java


There are mainly two types of exceptions: user-defined and built-in.

1. Built-in Exceptions
These exceptions are present in Java libraries.
There are two types of built-in exceptions in Java:

1. Checked Exception
Checked exceptions are classes that inherit directly from the Throwable class,
with the exception of RuntimeException and Error. Examples include
IOException, SQLException, and so on. Checked exceptions are checked at
compilation time. They must be either caught by the code or declared in the
method signature using the throws keyword.
2. Unchecked Exception
Classes that inherit the RuntimeException class are known as unchecked
exceptions. Examples include ArithmeticException, NullPointerException,
and ArrayIndexOutOfBoundsException. Unchecked exceptions are not
checked at compile-time but rather at runtime by JVM. They do not need to be
explicitly caught or declared.

2. User-Defined Exceptions
User-defined exceptions are also known as custom exceptions derived from
the Exception class from java.lang package(Java package). The user
creates these exceptions according to different situations. Such exceptions
are handled using five keywords: try, catch, throw, throws, and finally.
We'll learn how to use these keywords in the Exception Handling Keywords
in Java sectionbelow.

Errors Vs. Exceptions in Java


Errors Exceptions

Belongs to the java.lang.Error


defined in java.lang.Exception package
class

Errors are of Unchecked type Exceptions can be both checked and unchecked.

Errors mainly occur during run-


Only the unchecked exceptions are encountered in run-ti
time.

Exceptions can be handled using exception-han


Errors are irrecoverable
mechanisms

Java Exception Handling Keywords


Java consists of five keywords to handle various kinds of custom exceptions.
They are:
Keyword Description

try The "try" keyword specifies an exception block.

catch specifies the code block to be executed if an exception occurs in the try block.

finally the finally block will always be executed whether an exception occurs or not

throw the "throw" keyword triggers an exception

throws The "throws" keyword declares an exception.

. try
 A try block consists of all the doubtful statements that can throw
exceptions.
 A try block cannot be executed on itself; it requires at least
one catch block or finally block.
 If an exception occurs, the control flows from the try-to-catch block.
 When an exception occurs in a try block, the appropriate exception
object is redirected to the catch block. This catch block handles the
exception according to its statements and continues the execution.

Syntax

try
{
//Doubtful Statements.
}

2. catch
 The catch block handles the exception raised in the try block.
 The catch block or blocks follow every try block.
 The catch block catches the thrown exception as its parameter and
executes the statements inside it.
 The declared exception must be the parent class exception, the
generated exception type in the exception class hierarchy, or a user-
defined exception.

Syntax

try
{
// code
}
catch(Exception e)
{
// code to handle exceptions
}

Examples IIlustrating Implementation of try-catch


blocks for Java Exception Handling in Java Online
Compiler
1. single try-catch block
2.
3. class Main
4. {
5. public static void main(String[] args)
6. {
7. try
8. {
9. // code that generate exception
10. int divideByZero = 5 / 0;
11. System.out.println("Rest of code in try block");
12. }
13. catch (ArithmeticException e) {
14. System.out.println("ArithmeticException => " + e.getMessage());
15. }
16. }
}

Run Code >>

In the above code, we have put the "int divideByZero=5/0" in the try
block because this statement must not be executed if the denominator
is 0. If the denominator is 0, the statements after this statement in the
try block are skipped. The catch block catches the thrown exception as
its parameter and executes the statements inside it.

Output
ArithmeticException => / by zero
3. finally
The finally block in Java always executes even if there are no exceptions.
This is an optional block. It is used to execute important statements such as
closing statements, releasing resources, and releasing memory. There could
be one final block for every try block. This finally block executes after
the try...catch block.

Syntax

try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}

Example of Java Exception Handling using finally


block in Java Playground

class Main
{
public static void main(String[] args)
{
try
{
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " + e.getMessage());
}
finally
{
System.out.println("This is the finally block");
}
}
}
Run Code >>
In this Java example, trying to divide by zero results in
an ArithmeticException that is caught and accompanied by an error
message. The "finally" block also always runs, printing "This is the finally
block" whether or not an exception was raised.
Output
ArithmeticException => / by zero
This is the finally block

Advantages of Exception Handling in Java


 It helps to find which type of errors occur.
 It helps to complete the program executions.
 It allows the program to run continuously without any disruption.
 It provides the ability to catch the specific exception that occurred in the
program.
 It also helps the developers to write cleaner code and learn how to
handle exceptions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy