0% found this document useful (0 votes)
4 views15 pages

Chapter 8 Exception

Chapter 8 discusses exception handling in Java, explaining that exceptions are unexpected events that disrupt program execution. It categorizes exceptions into built-in (checked and unchecked) and user-defined exceptions, and introduces Java keywords such as try, catch, and finally for handling exceptions. The chapter also provides examples of exception handling techniques and the differences between checked exceptions, which are verified at compile-time, and unchecked exceptions, which are not.
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)
4 views15 pages

Chapter 8 Exception

Chapter 8 discusses exception handling in Java, explaining that exceptions are unexpected events that disrupt program execution. It categorizes exceptions into built-in (checked and unchecked) and user-defined exceptions, and introduces Java keywords such as try, catch, and finally for handling exceptions. The chapter also provides examples of exception handling techniques and the differences between checked exceptions, which are verified at compile-time, and unchecked exceptions, which are not.
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

Chapter:8

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:

Major reasons why an exception Occurs:


Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file

Exception Hierarchy:

All exception and error types are subclasses of class Throwable, which
is the base class of the hierarchy.
One branch is headed by Exception.
This class is used for exceptional conditions that user programs should
catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
Types of Java Exceptions:

There are mainly two types of exceptions:


checked and unchecked.
An error is considered as the unchecked exception.
there are two types of exceptions namely:
Exceptions can be categorized in two ways:

1) Built-in Exceptions
 Checked Exception
 Unchecked Exception

2).User-Defined Exceptions

Built-in Exceptions:

Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
The built-in-exceptions are classified into two types Checked exception
and unchecked exception.

[Link] Exceptions:

Checked exceptions are called compile-time exceptions


Because these exceptions are checked at compile-time by the compiler.
Checked exception is also called IO exceptions.
Example:
import [Link].*;
class SCE // Main class
{
public static void main(String args[]) // Main driver method
{
// Reading content from file by passing local directory path
// where file should exists
FileInputStream CSE = new FileInputStream("/Desktop/[Link]");
// This file does not exist in the location
// This constructor FileInputStream
// throws FileNotFoundException which
// is a checked exception
}
}
Output:
javac /tmp/ekGroR0BeB/[Link]
/tmp/ekGroR0BeB/[Link]: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
= new FileInputStream("/Desktop/[Link]");
^
1 error

[Link] Exceptions:

The unchecked exceptions are just opposite to the checked exceptions.


The compiler will not check these exceptions at compile time.
In simple words, if a program throws an unchecked exception, and even
if we didn’t handle or declare it,
the program would not give a compilation error.

Example:

import [Link];
import [Link];
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file = new File("E://[Link]");
FileReader fr = new FileReader(file);
}
}
Output:

javac /tmp/ekGroR0BeB/FilenotFound_Demo.java
/tmp/ekGroR0BeB/FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

3) Error:

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Example:

public class ErrorExample


{
public static void main(String args[])
{
//method calling
recursiveDemo(10);
}
public static void recursiveDemo(int i)
{
while(i !=0)
{
//increments the variable i by 1
i=i+1;
//recursive called method
recursiveDemo(i);
}
}
}
Output:

java -cp /tmp/ekGroR0BeB ErrorExample


Exception in thread "main" [Link]
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])
……………………………………………………………

……………………………………………………………

at [Link]([Link])

User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases, users can also create
exceptions, which are called ‘user-defined Exceptions’.
Example:
class MyException extends Exception
{
}
// A Class that uses above MyException
public class setText
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex)
{
[Link]("Caught");
[Link]([Link]());
}
}
}

Output:
Caught
Null
Java Exception Keywords:
Java provides five keywords that are used to handle the exception.

Keyword Description

The "try" keyword is used to specify a block where we should place an


try exception code. It means we can't use try block 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


catch try block which means we can't use catch block alone. It can be followed
by finally block later.

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

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

The "throws" keyword is used to declare exceptions. It specifies that there


throws may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.
Example Program:1

Exception handling using try...catch

public class JavaExceptionExample


{
public static void main(String args[])
{
try
{
int data=100/0; //code that may raise exception
}
catch(ArithmeticException e)
{
[Link](e);
}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:
[Link]:
/ by zero rest of the code...
Example Program:2 Java Exception Handling using finally block

class Main
{
public static void main(String[] args)
{
try
{
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
[Link]("ArithmeticException => " + [Link]());
}
finally
{
[Link]("Finally Block Completed Successfully");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block
Example Program:3

Exception handling using Java throw


import [Link].*;
class Main
{
// declareing the type of exception
public static void findFile() throws IOException
{
// code that may generate IOException
File newFile = new File("[Link]");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args)
{
try
{
findFile();
}
catch (IOException e)
{
[Link](e);
}
}
}

Output:

[Link]: [Link] (No such file or directory)


Exception handling using Java throw

Example:4

public class Main


{
static void checkAge(int age)
{
if (age < 21)
{
throw new ArithmeticException("Access denied - You must be at
least 22 years old.");
}
else
{
[Link]("Access Granted - You are Eligible for Indian
Civil Services");
}
}
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 21...)
}
}
Output:
Exception in thread "main" [Link]:
Access denied - You must be
at least 22 years old.
at [Link]([Link])
at [Link]([Link])
Example:5
public class TestThrow
{
//defining a method
public static void checkNum(int num)
{
if (num < 1)
{
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else
{
[Link]("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args)
{
TestThrow obj = new TestThrow();
[Link](-3);
[Link]("Rest of the code..");
}
}

Output:
Exception in thread "main" [Link]:
Number is negative, cannot calculate square
at [Link]([Link])
at [Link]([Link])
Example:6

public class TestThrows


{
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
//main method
public static void main(String[] args)
{
TestThrows obj = new TestThrows();
try
{
[Link]([Link](45, 0));
}
catch (ArithmeticException e)
{
[Link]("\nNumber cannot be divided by 0");
}
[Link]("Rest of the code..");
}
}

Output:
Number cannot be divided by 0
Rest of the code..
Example:6
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
[Link]("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
[Link]("caught in main() method");
}
}
}
End of the Chapter

You might also like