Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.
2. Here, i will discuss what is an
exception and how it can be
handled in java programming
language.
3. An Exception can be anything which interrupts the normal
flow of the program. When an exception occurs program
processing gets terminated and doesn’t continue further.
In such cases we get a system generated error message. In
other words, an exception is a run-time error. The good
thing about exceptions is that they can be handled.
What is an exception?
4. Exception can occur at runtime (known as runtime exceptions) as
well as at compile-time (known Compile-time exceptions).
In example-
Dividing a number by zero.
Accessing an element that is out of bounds of an array.
Trying to store incompatible data elements.
Trying to convert from string to specific data value.
File errors: not found, permissions error etc.
Corrupting memory.
Network connection error.
When an exception can occur?
5. Exception handling allows us to control the normal flow of
the program by using exception handling in program.
It throws an exception whenever a calling method
encounters an error providing that the calling method
takes care of that error.
It also gives us the scope of organizing and differentiating
between different error types using a separate block of
codes. This is done with the help of try-catch blocks.
Advantages of Exception Handling
6. If an exception is raised, which has not been handled by programmer
then program execution can get terminated and system prints a non
user friendly error message.
We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the
time exception occurs due to bad data provided by user.
Why to handle exception?
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
7. In computer languages that do not support exception
handling, errors must be checked and handled manually—
typically through the use of error codes, and so on. This
approach is as cumbersome as it is troublesome. Java’s
exception handling avoids these problems and, in the process,
brings run-time error management into the object oriented
world.
Exception Handling in Java
11. try {
// block of code to monitor for errors
// throw exception explicitly (mainly custom exception)
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
General Form of an Exception Handling Block
12. Java try block is used to enclose the code that might throw
an exception. It must be used within the method.
Possible forms of try statement:
1. try-catch
2. try-finally
3. try-catch-finally
If an exception occurs in a try statement, execution of the try
statement is terminated. A catch statement handles the
exeception thrown by the try statement.
Java try Block
13. Java catch block is used to handle the Exception. It must be
used after the try block only. If you have to perform
different tasks at the occurrence of different Exceptions,
use java multi catch block with a single try.
Rules for multiple catch block:
1. At a time only one Exception is occured and at a time only
one catch block is executed.
2. All catch blocks must be ordered from most specific to
most general i.e. catch for ArithmeticException must
come before catch for Exception .
Java catch Block
15. Task1 is completed
rest of the code…
public class TestMultipleCatchBlock {
public static void main (String args[]) {
try {
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) {
System.out.println("common task completed"); }
System.out.println("rest of the code...");
}
}
16. Java finally block is a block that is used to execute
important code such as closing connection, stream etc. It is
always executed whether exception is handled or not. It
can be used to put "cleanup" code such as closing a file,
closing connection etc.
Rules for finally block:
1. For each try block there can be zero or more catch blocks,
but only one finally block.
2. The finally block will not be executed if program exits(either
by calling System.exit() or by causing a fatal error that causes
the process to abort).
Java finally Block
18. Task1 is completed
finally block is always executed
rest of the code…
public class TestMultipleCatchBlock {
public static void main (String args[]) {
try {
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) { System.out.println("common task completed"); }
finally { System.out.println(“finally block is always executed”); }
System.out.println("rest of the code...");
}
}
19. The Java throw keyword is used to explicitly throw an
exception mainly custom exception. We can throw either
checked or uncheked exception in java by throw keyword.
Syntax:
throw exception;
// throw custom exception
throw new IOException("sorry device error);
// throw IOException
Java throw Keyword
20. Exception in thread main java.lang.ArithmeticException:not valid
public class TestThrow1{
static void validate(int age) {
if(age<18) throw new ArithmeticException("not valid");
else System.out.println("welcome to vote");
}
public static void main(String args[]) {
validate(13);
System.out.println("rest of the code...");
}
}
21. The Java throws keyword is used to declare an exception. 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 normal flow can
be maintained.
Syntax:
return_type method_name() throws exception_class_name {
// method code
}
Java throws Keyword
22. No throw throws
1 Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to declare
an exception.
2 Checked exception cannot be
propagated using throw only.
Checked exception can be propagated
with throws.
3 Throw is followed by an instance. Throws is followed by class.
4 Throw is used within the method. Throws is used with the method
signature.
5 You cannot throw multiple
exceptions.
You can declare multiple exceptions e.g.
public void method() throws
IOException,SQLException
Difference between throw and throws in Java
23. Md. Arafat Islam
Roll: 150126
Department of Computer Science and Engineering
Pabna University of Science and Technology