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

uUNIT-III OOPC JAVA

An exception in Java programming is an abnormal situation that disrupts normal program execution flow. When an exception occurs, the program terminates without executing the remaining code. Exceptions can be categorized as built-in or user-defined. Built-in exceptions include checked exceptions, which must be declared or handled, and unchecked exceptions, which do not require declaration. The try-catch block is used to handle exceptions, with the try block containing the code that may throw an exception and the catch block containing the code to handle the exception.

Uploaded by

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

uUNIT-III OOPC JAVA

An exception in Java programming is an abnormal situation that disrupts normal program execution flow. When an exception occurs, the program terminates without executing the remaining code. Exceptions can be categorized as built-in or user-defined. Built-in exceptions include checked exceptions, which must be declared or handled, and unchecked exceptions, which do not require declaration. The try-catch block is used to handle exceptions, with the try block containing the code that may throw an exception and the catch block containing the code to handle the exception.

Uploaded by

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

An exception in java programming is an abnormal situation that is

araised during the program execution. In simple words, an


exception is a problem that arises at the time of program execution.
 When an exception occurs, it disrupts the program execution
flow. When an exception occurs, the program execution gets
terminated, and the system generates an error.
 It is an object which is thrown at runtime.
 The problem with the exception is, it terminates the program and
skip rest of the execution that means if a program have 100 lines
of code and at line 10 an exception occur then program will
terminate immediately by skipping execution of rest 90 lines of
code.
 Reasons for Exception Occurrence
 Several reasons lead to the occurrence of an exception. A few of
them are as follows.
• When we try to open a file that does not exist may lead to an
exception.
• When the user enters invalid input data, it may lead to an
exception.
• When a network connection has lost during the program
execution may lead to an exception.
• When we try to access the memory beyond the allocated range
may lead to an exception.
• The physical device problems may also lead to an exception.

 Exceptions can be categorized into two ways:
1. Built-in Exceptions
1. Checked Exception
2. Unchecked Exception
2. User-Defined Exceptions
 1.Built-in Exception
 Exceptions that are already available in Java libraries are
referred to as built-in exception. These exceptions are able
to define the error situation so that we can understand the
reason of getting this error.
 It can be categorized into two broad categories,
i.e., checked exceptions and unchecked exception.

 Checked Exception
 Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler.
 The compiler ensures whether the programmer handles the exception or not. The
programmer should have to handle the exception; otherwise, the system has shown a
compilation error.
 Unchecked 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.
 Usually, it occurs when the user provides bad data during the interaction with the program.
 User-defined Exception
 In Java, we can write our own exception class by extends the Exception class. We
can throw our own exception on a particular condition using the throw keyword.
For creating a user-defined exception, we should have basic knowledge
of the try-catch block and throw keyword.
 Class Not Found Exception in Java:
 ClassNotFoundException is a checked exception and occurs when the Java Virtual
Machine (JVM) tries to load a particular class and the specified class cannot be found
in the classpath.(Ex: when .class file is not available)
 InterruptedException:
 An InterruptedException is thrown when a thread is interrupted while it's waiting,
sleeping, or otherwise occupied. In other words, some code has called the
interrupt() method on our thread.
 IOException:
 The most common cause due to which an IOException is thrown is attempting to
access a file that does not exist at the specified location. Common exception classes
which are derived from IOException base class
are EndOfStreamException, FileNotFoundException, DirectoryNotFoundException et
c.
 InstantiationException:
 occurs when an application attempts to create an instance of a class using the
Class.newInstance() method, but the specified class object cannot be instantiated.
 SQL Exception:
 An exception that provides information about database related is also known as SQL
Exception.
 Arithmetic exception :
 It is a type of unchecked error in code that is thrown whenever there is a wrong
mathematical or arithmetic calculation in the code, especially during run time.
 NullPointerException :
 It is a run time exception. It is thrown when a null value is assigned to a reference
object and the program tries to use that null object.
1. EX:
2. int arr[] = null; // array is assigned a null value
3. System.out.println("The length of the array arr is: " + arr.length);
 ArrayIndexOutOfBoundsException :
 It occurs when we access an array with an invalid index. This means that either the
index value is less than zero or greater than that of the array’s length.
 NumberFormatException :
 It is a type of unchecked exception that occurs when we are trying to convert a string
to an int or other numeric value.
 InputMismatchException :
 It occurs when an input provided by the user is incorrect. The type of incorrect input
can be out of range or incorrect data type.
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.
 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.

 Java try-catch block:


 The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

 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 (
i.e., Exception) or the generated exception type.
 The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

 Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }
4. catch(Exception_class_Name ref)
5. {
6. }
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. }
 public class TryCatchExample2 {

 public static void main(String[] args) {
 try
 {
 System.out.println("hi");
 int data=50/0; //may throw exception
 }
 //handling the exception
 catch(ArithmeticException e)
 {
 System.out.println(“divide by zero “);
 }
 System.out.println("rest of the code");
 } }

 public class TryCatchExample2 {
 public static void main(String[] args) {
 try
 {
 System.out.println("hi");
 int data=50/0; //may throw exception
 }
 //handling the exception
 catch(ArrayIndexOutOfBoundsException e)
 {
 System.out.println(e);
 }
 System.out.println("rest of the code");
 } }

Java Catch Multiple Exceptions
 try block can be followed by one or more catch blocks.
 Each catch block must contain a different exception handler.
 So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.
• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
 Before Java 7, we had to catch only one exception type in each catch block.
 So, whenever we needed to handle more than one specific exception but take some
action for all exceptions,
 we had to have more than one catch block containing the same code.
 Starting from Java 7.0, it is possible for a single catch block to catch multiple
exceptions by separating each with | (pipe symbol) in the catch block.
 The Java throw keyword is used to throw an exception explicitly.
 The throw keyword in Java is used to explicitly throw an exception
from a method or any block of code. We can throw either checked
or unchecked exception. The throw keyword is mainly used to
throw custom exceptions.
 Creating our own Exception is known as custom exception or user-
defined exception. Basically, Java custom exceptions are used to
customize the exception according to user need.
 To indicate that something goes wrong, we use throw keyword.
 The throw keyword is used to throw an exception instance
explicitly from a try block to corresponding catch block. That
means it is used to transfer the control from try block to
corresponding catch block.
 The throw keyword must be used inside the try blcok. When JVM encounters
the throw keyword, it stops the execution of try block and jump to the
corresponding catch block.

 The syntax of the Java throw keyword is given below.


1. throw new exception_class("error message");
example of throw IOException.
1. EX:
2. throw new IOException("sorry device error");
 Where the Instance must be of type Throwable or subclass of Throwable.
 For example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.
 import java.util.Scanner;
public class Sample {
 public static void main(String[] args) {
 Scanner input = new Scanner(System.in);
 int num1, num2, result;
 System.out.print("Enter any two numbers: ");
 num1 = input.nextInt();
 num2 = input.nextInt();
 try {
 if(num2 == 0)
 throw new ArithmeticException("Division by zero is not posible");
 result = num1 / num2;
 System.out.println(num1 + "/" + num2 + "=" + result);
 }
 catch(ArithmeticException ae) {
 System.out.println("Problem info: " + ae.getMessage());
 }
 System.out.println("End of the program");
 } }
Throws keyword in java
 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 the normal flow of the program can be maintained.
 In our program, if there is chance of raising checked exception, then we will
use throws keyword. Otherwise the code wont be compiled.
 throws is a keyword in Java that is used in the signature of a method to
indicate that this method might throw one of the listed type exceptions.
 The caller to these methods has to handle the exception using a try-catch
block.
 The throws keyword specifies the exceptions that a method can throw to the
default handler and does not handle itself. That means when we need a
method to throw an exception automatically,
 we use throws keyword followed by method declaration.
 Syntax of Java throws
1. return_type method_name() throws exception_class_name
2. {
3. //method code
4. }
5. throws keyword is required only for checked exceptions and usage of the
throws keyword for unchecked exceptions is meaningless.
6. With the help of the throws keyword, we can provide information to the caller
of the method about the exception.
7. Which exception should be declared?
8. Ans: Checked exception only, because:
unchecked exception: under our control so we can correct our code.
 import java.io.*;
 class ThrowsEx{
 public static void main(String[] args) {

 PrintWriter pw = new PrintWriter("E:\\Data1.txt");


 pw.write("mahender");

 }
 }
What is the difference between throw and
throws?
throw throws
It is used in method definition, to
It is used to create a new
declare that a risky method is
Exception object and throw it
being called.
Using throw keyword you can Using throws keyword you can
declare only one Exception at a declare multiple exception at a
time time.
Example: Example:
throw new IOException(“can not throws IOException,
open connection”); ArrayIndexBoundException;

You might also like