0% found this document useful (0 votes)
24 views

Exception Handling in Java

Exception handling in Java allows programmers to handle runtime errors and maintain normal program flow. There are two types of exceptions: checked exceptions which are compiler-enforced and unchecked exceptions which occur at runtime. The try, catch, and finally keywords allow specifying exception handling code.

Uploaded by

pc03198007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Exception Handling in Java

Exception handling in Java allows programmers to handle runtime errors and maintain normal program flow. There are two types of exceptions: checked exceptions which are compiler-enforced and unchecked exceptions which occur at runtime. The try, catch, and finally keywords allow specifying exception handling code.

Uploaded by

pc03198007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Exception Handling in Java:

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.

Exception Handling is a mechanism to handle runtime errors


such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
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.

Hierarchy of Java Exception classes:


Types of Java Exceptions:

There are mainly two types of exceptions:

1) Checked Exception

The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions.
For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception

The classes that inherit the RuntimeException are known as


unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they
are checked at runtime.

Java Exception Keywords:

Keyword Description

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

catch The "catch" block is used to handle the exception.

finally The "finally" block is used to execute the necessary code of the program.

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

throws The "throws" keyword is used to declare exceptions.

Throw Exception:
In Java, exceptions allows us to write good quality codes where
the errors are checked at the compile time instead of runtime
and we can create custom exceptions making the code recovery
and debugging easier.

Java throw keyword:


The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The
Exception has some message with it that provides the error
description. These exceptions may be related to user inputs,
server, etc.

The syntax of the Java throw keyword :

throw new exception_class("error message");

throw IOException :

throw new IOException("sorry device error");

Bulit in Exceptions:
There are given some scenarios where unchecked exceptions
may occur. They are as follows:

1) ArithmeticException:

If we divide any number by zero, there occurs an


ArithmeticException.

1. int a=50/0;//ArithmeticException

2) NullPointerException:

If we have a null value in any variable, performing any operation


on the variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) NumberFormatException:

If the formatting of any variable or number is mismatched, it may


result into NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) ArrayIndexOutOfBoundsException:

When an array exceeds to it's size, the


ArrayIndexOutOfBoundsException occurs.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Custom Exception:


In Java, we can create our own exceptions that are derived classes
of the Exception class. Creating our own Exception is known as
custom exception or user-defined exception.

we have passed a string to the constructor of superclass i.e.


Exception class that can be obtained using getMessage() method
on the object we have created.

Use custom exceptions:

o To catch and provide specific treatment to a subset of


existing Java exceptions.
o Business logic exceptions: These are the exceptions related
to business logic and workflow.
Create a custom exception named
WrongFileNameException

1. public class WrongFileNameException extends Exception


2. {
3. public WrongFileNameException(String errorMessage)
4. {
5. super(errorMessage);

Example 2:

TestCustomException:

1. // class representing custom exception


2. class MyCustomException extends Exception
3. {
4.
5. }
6.
7. // class that uses custom exception MyCustomException
8. public class TestCustomException2
9. {
10. // main method
11. public static void main(String args[])
12. {
13. try
14. {
15. // throw an object of user defined exception
16. throw new MyCustomException();
17. }
18. catch (MyCustomException ex)
19. {
20. System.out.println("Caught the exception");
21. System.out.println(ex.getMessage());
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }

Java try block:


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

If an exception occurs at the particular statement in the try block,


the rest of the block code will not execute

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

Syntax of Java try-catch:

1. try{
2. //code that may throw an exception
3. }
4. catch(Exception_class_Name ref)
5. {
6. }

Syntax of try-finally block:

1. try{
2. //code that may throw an exception
3. }
4. finally{
5. }

Java catch block:

Java catch block is used to handle the Exception by declaring


the type of exception within the parameter. The declared
exception must be the parent class exception .
The catch block must be used after the try block only.
Example 1

Try Catch Example:

1. public class TryCatchExample1 {


2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }

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

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }

Output:
java.lang.ArithmeticException: / by zero
rest of the code

the rest of the code is executed, i.e., the rest of the


code statement is printed.

Example 3

try block that will not throw an exception.

1. public class TryCatchExample3 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement
will not exceute
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }

Output:
java.lang.ArithmeticException: / by zero

if an exception occurs in the try block, the rest of the block code
will not execute.

Example 4

1. public class TryCatchExample4 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception class
9. catch(Exception e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }

Output:
java.lang.ArithmeticException: / by zero
rest of the code

Example 5

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }

Output:
Can't divided by zero

Throw Keyword:

Example 1: Throwing Unchecked Exception

If the age is less than 18, we are throwing the


ArithmeticException otherwise print a message welcome to vote.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible t
o vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }

Output:
.

Example 2: Throwing Checked Exception:

Every subclass of Error and RuntimeException is an


unchecked exception

1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {

7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desk
top\\abc.txt");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }
Output:

Example 3: Throwing User-defined Exception:

Exception is everything else under the Throwable class.


1. // class represents user-defined exception
2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-
defined exception");
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }

Output:

Stack Trace Elements :


The stack frames represent the movement of an application
during the execution of the program. It traces the locations
where exception raised.

It collects the information of all the methods that are invoked by


a program.
The JVM automatically produces the stack trace when an
exception is thrown.

The StackTraceElement class provides a constructor that parses


four parameters as an argument and creates a stack trace .
public StackTraceElement(String declaringClass, String method
Name, String fileName, int lineNumber)

Parameters:

o declaringClass: the qualified name of the class that


contains the execution point.
o methodName: It represents the method name that
contains the execution point.
o fileName: It represents the file name that contains the
execution point.
o lineNumber: It represents the line number of the source of
the execution point.

Java Stack Trace Example:

1. public class StackTraceExample


2. {
3. public static void main(String args[])
4. {
5. demo();
6. }
7. static void demo()
8. {
9. demo1();
10. }
11. static void demo1()
12. {
13. demo2();
14. }
15. static void demo2()
16. {
17. demo3();
18. }
19. static void demo3()
20. {
21. Thread.dumpStack();
22. }
23. }
24.

Byte Streams:

Java byte streams are used to perform input and output of 8-bit
bytes. Though there are many classes related to byte streams
but the most frequently used classes
are, FileInputStream and FileOutputStream.

Example
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Character Streams:
Java Byte streams are used to perform input and output of 8-bit
bytes, whereas Java Character streams are used to perform
input and output for 16-bit Unicode.

Though there are many classes related to character streams


but the most frequently used classes
are, FileReader and FileWriter.

Example
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

You might also like