KEMBAR78
Chapter Five | PDF | Java (Programming Language) | Programming Paradigms
0% found this document useful (0 votes)
11 views30 pages

Chapter Five

Uploaded by

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

Chapter Five

Uploaded by

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

1

Chapter Five
Exception Handling

Compiled By: Nigusu Y. (Nigusu.Yitayal@inu.edu.et )


Exception
o An exception is a problem that arises 2during the execution of a program.

o When an Exception occurs the normal flow of the program is disrupted and

the program/Application terminates abnormally, which is not recommended,


therefore, these exceptions are to be handled.

o An exception is an abnormal condition that arises in a code sequence at run

time.

o In other words, an exception is a run-time error.

o 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.
Con’t
o In java, exception is an event that disrupts the normal flow of the program.
3
o It is an object which is thrown at runtime.

o The major reasons why an exception occurs are listed below.

• Invalid user input

• Device failure

• Loss of network connection

• Physical limitations (out-of-disk memory)

• Code errors

• Opening an unavailable file

o Some of these exceptions are caused by user error, others by programmer

error, and others by physical resources that have failed in some manner.
Exception Hierarchy
o All exception classes are subtypes of the4 java.lang.Exception class.

o The exception class is a subclass of the Throwable class.

o Other than the exception class there is another subclass called Error which is

derived from the Throwable class.

o Errors are abnormal conditions that happen in case of severe failures, these are not

handled by the Java programs.

o Errors are generated to indicate errors generated by the runtime environment.

Example: JVM is out of memory.

o Normally, programs cannot recover from errors.

o The Exception class has two main subclasses: IOException class and

RuntimeException Class.
o All exception types are subclasses of class Throwable, which is at the top of
exception class hierarchy.
5
Types of Exception
o There are mainly two types of exceptions: checked and unchecked where error
6
is considered as unchecked exception.

o The sun microsystem says there are three types of exceptions:

1. Checked exceptions

✓ A checked exception is an exception that occurs at the compile time, these are
also called as compile time exceptions.

✓ These exceptions cannot simply be ignored at the time of compilation, the


programmer should take care of (handle) these exceptions.

✓ The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions

Example: IOException, SQLException


Example : checked exception
import java.io.File;
7
import java.io.FileReader;
public class FileDemo
{
public static void main(String args[])
{
File file = new File("NetBeansProjects\excep1\src\excep1//file.txt");
FileReader fr = new FileReader(file);
}
}
o If you try to compile the above program, you will get the following exceptions.

(FileNotFoundException may occurred)


8
2. Unchecked exceptions
✓ An unchecked exception is an exception that occurs at the time of execution.
9
✓ These are also called as Runtime Exceptions.

✓ These include programming bugs, such as logic errors or improper use of an


API.

✓ The classes that extend RuntimeException are known as unchecked exceptions.

✓ Unchecked exceptions are not checked at compile-time rather they are checked
at runtime.

o ArithmeticException: If we divide any number by zero, there occurs an

ArithmeticException.

int a=50/0;//ArithmeticException
o NullPointerException: If we have null value in any variable, performing any

operation by the variable occurs an NullPointerException.


10
String s=null;

System.out.println(s.length());//NullPointerException

o NumberFormatException : The wrong formatting of any value may occur

✓ Suppose a string variable that have characters, converting this variable into
digit will occur NumberFormatException.
String s="abc";

int i=Integer.parseInt(s); // NumberFormatException

o ArrayIndexOutOfBoundsException: If you are inserting any value in the wrong

index.

int num[] = {1, 2, 3, 4};

System.out.println(num[5]);
11
3. Error
✓ Error defines as exceptions that are not expected to be caught under normal
12
circumstances by your program.

✓ Exceptions of type error are used by the Java run-time system to indicate
errors having to do with the run-time environment, itself.

✓ These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer and is not recoverable.

✓ Errors are typically ignored in your code because you can rarely do anything
about an error.

✓ They are also ignored at the time of compilation.

✓ OutOfMemoryError, VirtualMachineError, AssertionError is an example


of such an error.
Exception Handling in Java
o The exception handling in java is one13of the powerful mechanism to handle the

runtime errors so that normal flow of the application can be maintained.

o A Java exception is an object that describes an exceptional (error) condition that

has occurred in a piece of code.

o When an exceptional condition arises, an object representing that exception is

created and thrown in the method that caused the error.

o That method may choose to handle the exception itself, or pass it on. Either way,

at some point, the exception is caught and processed.

o Exceptions can be generated by the Java run-time system, or they can be manually

generated by your code.

o Exceptions thrown by Java relate to fundamental errors that violate the rules of

the Java language or the constraints of the Java execution environment.


o Manually generated exceptions are typically used to report some error condition

to the caller of a method.


14
o Java exception handling is managed via five keywords: try, catch, throw,

throws, and finally.

o In Java, it is possible to define two categories of Exceptions and Errors.

• JVM Exceptions − These are exceptions/errors that are exclusively or


logically thrown by the JVM. Examples: NullPointerException,
ArrayIndexOutOfBoundsException, ClassCastException.

• Programmatic Exceptions − These exceptions are thrown explicitly by the


application or the API programmers. Examples: IllegalArgumentException,
IllegalStateException.

o An uncaught exception is an exception that occurs for which there are no

matching catch blocks.


Try …Catch Block
o Exception handling provides a powerful mechanism for controlling complex programs that
15
have many dynamic run-time characteristics.

o Java try block is used to enclose the code that might throw an exception. It must be used

within the method.

o Java try block must be followed by either catch or finally block.

o Syntax of java try-catch:


try {
// block of code to monitor for errors
}
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
}
o Java catch block is used to handle the Exception.

o It must be used after the try block only and can be used multiple catch block with a
single try. 16

o Example: Problem without exception handling

public class TryCatch


{
public static void main(String args[])
{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Program Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
o Let's see the solution of above problem by java try-catch block.

public class trycatch2{


17
public static void main(String args[]){

try {

int data=50/0;

catch(ArithmeticException e){

System.out.println(e);

System.out.println("rest of the code...");

} Output:
Exception in thread main java.lang.ArithmeticException:/
} by zero
rest of the code...
Internal working of java try-catch block

18
Java exception handling example
public class Division {

public static void main(String[] args) { 19

int a, b, result;

Scanner input = new Scanner(System.in);

System.out.println("Input two integers");

a = input.nextInt();

b = input.nextInt(); // try block

try {

result = a / b;

System.out.println("Result = " + result); } // catch block

catch (ArithmeticException e) {

System.out.println("Exception caught: Division by zero.");

} }}
❖ If you have to perform different tasks at the occurrence of different Exceptions, use java multi

catch block.
public class CatchBlocks{ 20
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...");

} }

❖ At a time only one Exception is occurred and at a time only one catch block is executed.
Finally block
o Java finally block is a block that is used to execute important code such as
21
closing connection, stream etc.

o Java finally block is always executed whether exception is handled or not.

o Java finally block follows try or catch block.

o If you don't handle exception, before terminating the program, JVM executes

finally block(if any).

o Finally block in java can be used to put "cleanup" code such as closing a file,

closing connection etc.


o There are three different cases where java finally block can be used.
1. Java finally block executed where exception does not occur.
class FinallyBlock
{ 22
public static void main(String args[])
{
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
2. Java finally block executed where exception occurs and not handled.
class FinallyBlock1
{
public static void main(String args[]) 23
{
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
3. Java finally block executed where exception occurs and handled.
public class FinallyBlock2{
24
public static void main(String args[]){

try{

int data=25/0;

System.out.println(data); }

catch(ArithmeticException e){System.out.println(e);}

finally{System.out.println("finally block is always executed");}

System.out.println("rest of the code...");

} }

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

finally block is always executed

rest of the code...


throw exception
o The Java throw keyword is used to explicitly
25 throw an exception.

o We can throw either checked or uncheked exception in java by throw

keyword.

o The throw keyword is mainly used to throw custom exception (User defined

exception).

o Consider the following example:

✓ We have created the validate method that takes integer value as a


parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
public class Throw1{

static void validate(int age){


26
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...");

Output: Exception in thread main java.lang.ArithmeticException: not valid


Throws Exception
o The throws keyword is used to declare an exception.
27
o 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.

o Exception Handling is mainly used to handle the checked exceptions.

o If there occurs any unchecked exception such as NullPointerException, it is


programmers fault that he is not performing check up before the code being used.

o Syntax of java throws

Type methodNname() throws exceptionClassName

//method code

}
//Program if exception occurs
import java.io.*;
28
class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
class Testthrows4
{
public static void main(String args[])throws IOException //declare exception
{
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
//Program if exception does not occur
import java.io.*;
class ThrowsExc 29
{
void method()throws IOException
{
System.out.println("device operation performed");
} }
class Excpthrows
{
public static void main(String args[])throws IOException
//declare exception
{
ThroeExc exc=new ThroeExc();
m.method();
System.out.println("normal flow...");
}
}
throw Vs throws
30
No. throw throws
1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.

2) Checked exception cannot be propagated Checked exception can be propagated with


using throw only. 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.

You might also like