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

Exception Handling

The document discusses different types of errors that can occur in computer programs including syntax errors, runtime errors, and logic errors. It also defines checked and unchecked exceptions in Java and describes how exception handling works using try, catch, throws, and finally keywords.
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)
42 views

Exception Handling

The document discusses different types of errors that can occur in computer programs including syntax errors, runtime errors, and logic errors. It also defines checked and unchecked exceptions in Java and describes how exception handling works using try, catch, throws, and finally keywords.
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/ 16

UNIT-V

Exception Handling

Types of Errors

Que:
1. List and explain different types of errors.
2. Explain types of errors with example.
3. List types of Errors in exceptional handling and explain any one of them.
4. List types of error in Java.
Ans:

 There are basically three types of errors that may arise during computer programs
execution:

1. Syntax errors
2. Runtime errors
3. Logic errors

1. Syntax errors
 Syntax Errors, also known as Compilation errors are the most common type of errors.
 Most Syntax errors are caused by mistakes that you make when writing code.
 Common examples are:
 Misspelled variable and function names
 Missing semicolons
 Improperly matches parentheses, square brackets, and curly braces
 Incorrect format in selection and loop statements

2. Runtime errors
 Run-time errors are those that appear only after you compile and run your code. It will
occur when your program attempts an operation that is impossible to carry out.
 You can fix most run-time errors by rewriting the faulty code, and then recompiling and
running it.
 Common examples are:
 Trying to divide by a variable that contains a value of zero
 Trying to open a file that doesn't exist
 There is no way for the compiler to know about these kinds of errors when the program is
compiled.

3. Logic errors
 Your code may compile and run without any Syntax Errors or Run-time Errors, but the
output of an operation may produce unwanted or unexpected results in response to user
actions. These types of errors are called Logic Errors.
 Common examples are:
 Multiplying when you should be dividing
 Adding when you should be subtracting
 Opening and using data from the wrong file
 Displaying the wrong message

Exception
Que:
1. Compare checked and Unchecked Exception.
Ans:
 An exception (or exceptional event) is a problem that arises during the execution of a
program.
 When an Exception occurs the normal flow of the program is disrupted and the program
terminates abnormally.therefore, these exceptions are to be handled.
 Following are some scenarios where an exception occurs.
 A user has entered an invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of communications or the JVM has run
out of memory.

 Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.

 Based on these, we have three categories 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.

 For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.

2. Unchecked exceptions

 An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions.

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


an API.
 For example, if you have declared an array of size 5 in your program, and
trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.

3. Errors

 Error is a problem that arises, which is not under the control of the user or
the programmer.

 For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.

 These are not exceptions at all.

Differentiate between Exception and Error


Sr.
Error Exception
No.
1 Error is a problem that arises, which is not Exception is a problem that arises during
under the control of the user or the the execution of a program.
programmer.
Error is which nobody can control or guess. Exception can be guessed and so it can be
2
when it occurs,so error cannot be handled. handled.
3 Error can Terminates the program Exception do not terminate the program.
An Error is unrecoverable: An Exception can be caught and recovered:
4
OutOfMemoryError means that the JVM has ArrayIndexOutOfBoundsException means
no more memory to contain you tried to access a position of an Array
that does not exist - no big deal.
Error message is standard given by JVM. Exception will give user friendly message
5
which is defined in exception handling.
For example: For Example:
6
thread dead,out of memory,overflow. Divided by Zero, File doesn’t Exist

Exception Handling in Java

Que:
1. Explain Exception Handling.
2. Explain basic concept of Exception Handling.
Ans:
 Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
 Program statements that you want to monitor forexceptions are contained within a try
block.
 If an exception occurs within the try block, it isthrown. Your code can catch this
exception (using catch) and handle it.
 System-generated exceptions are automatically thrown by the Java run-time system.
 Tomanually throw an exception, use the keyword throw.
 Any exception that is thrown out ofa method must be specified as such by a throws
clause.
 Any code that absolutely must beexecuted after a try block completes is put in a
finallyblock.
 This is the general form of an exception-handling block:
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
}
Try…Catch
Que:
1. Explain Try and Catch with suitable example.
2. Explain ‘try’ and ‘catch’ statements in exceptional handling of Java language.
3. Write a program and explain try…catch block.
4. Explain ArrayIndexOutOfBound Exception in Java with example.
Ans:

 Code that you want to monitor, put inside in Try block.


 Immediately following the try block,include a catch block that specifies theexception
type that we wish to catch.
 Following program includes try block and catch block which processes the
ArithmeticException generated by the division-by-zero.
 Example,
class AE
{
public static void main(String args[])
{
int d, a;
try// monitor a block of code.
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)// catch divide-by-zero error
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
 Once an exception is thrown,program control transfers out of the try block into catch
block.

Multiple Catch Blocks


Que:
1. Explain Multiple Catch block with program example.
2. Explain multiple catch blocks with example.
Ans:

 More than one exception could be raised by a single piece of code.


 To handle this type of situation,you can specify two or more catch block.
 When an exception is thrown,each catch statement is inspected in order, and whose type
is matches that of the exception is executed.
 After one catch statement executed,the other are bypassed and execution continues after
the try/catch block.
 Syntax
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block
}
 Example,
class ME
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
int c[]={1};
c[42]=99;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero." + e);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out of Bound"+e);
}
System.out.println("After catch statement.");
}
}

Throw, Throws and Finally


Que:
1. Explain throw & throws with example.
2. Explain throw and finally in Exception Handling of java language.
3. Compare following:
(ii) throwVs throws
4. Explain following
(i) throws (ii) checked exception
5. Explain following
(i) throw (ii) finally
Ans:

Throw
 System-generated exceptions are automatically thrown by the Java run-time system.
 To manually throw an exception, the throw keyword is used.
 it is used to explicitly throw exception in java.
 The general form of throw is shown here:

throw ThrowableInstance;

 Here, ThrowableInstancemust be an object of type Throwable or a subclass of


Throwable.
 The flow of execution stops immediately after the throw statement, any
subsequentstatements are not executed.
 The nearest enclosing try block is inspected to see if it has acatch statement that matches
the type of exception.
 If it does find a match, control istransferred to that statement. If not, then the next
enclosing try statement is inspected, andso on.
 Example,

class throwDemo
{
static void validate(int age)
{
try
{
if(age<16)
{
throw new ArithmeticException("Invalid Age");
}
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}

public static void main(String args[])


{
int age=10;

validate(age);
}
}

Throws

 The throws keyword is used to declare that a method may throw one or some
exceptions.
 It can propagate exception to the calling method.
 Calling method must have to catch the exception which is thrown by the throws
keyword.
 Programmer hasto handle the thrown exception.
 It can throws checked exception.
 All other exceptions that a methodcan throw must be declared in the throws clause.
 The throws keyword must be followed by Throwable class or one of its subclasses.
 This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws Exception1, Exception2


{
// body of method
}

 Exception1, Exception2, …are the exception class, must be subclass


of Throwable class.
 For Example:
class testThrow
{
static void divide() throws ArithmeticException
{
int a=8,d=0;
a=42/d;
}

public static void main(String args[])


{
try
{
divide();
}

catch(ArithmeticException e)
{
System.out.println("Please Enter Valid Data");
}

}
}

Finally

 Finallycreates a block of code that will be executed after a try/catch block hascompleted.
 The finally block willexecute whether or not an exception is thrown.
 If an exception is thrown, the finallyblock will execute even if no catch statement matches
the exception.
 The finally clause is optional. The finally block follows a try block or a catch block.
 Syntax:
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
finally
{
// The finally block always executes.
}

 Example:
class AE
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e) // catch divide-by-zero error
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("The finally statement is executed");

}
System.out.println("After catch statement.");

}
}

Checked and Unchecked Exceptions in Java, there are two types of exceptions in java: First is
predefined exceptions, and second user-defined exceptions.
The predefined exceptions are those exceptions that are already defined by the java system.
All the predefined exceptions are further divided into two groups:
1. Checked Exceptions
2. Unchecked Exceptions

Checked Exceptions in Java

Checked exceptions are those exceptions that are checked by the java compiler itself at
compilation time and are not under runtime exception class hierarchy. If a method throws a
checked exception in a program, the method must either handle the exception or pass it to a
caller method.
Checked exceptions must be handled either by using try and catch block or by using throws
clause in the method declaration. If not handles properly, it will give a compile-time error.
Most people have confusion and say that checked exceptions occur at compile-time, that is
wrong. All exceptions always occur at runtime only but some exceptions are detected at compile-
time and some other at runtime.
The exceptions that are checked by Java compiler at compilation time is called checked
exception in Java. All the exceptions except RuntimeException, Error, and their subclasses are
checked exceptions.

class test

void method(int n) throws InterruptedException

for(int i=0;i<n;i++)

System.out.println(i);

Thread.sleep(1000);

}
}

class demo

public static void main(String args[])

test m1=new test();

try

m1.method(5);

catch(InterruptedException e)

System.out.println("exception occur");

Difference between throw and throws


Sr. throw throws
no.
1) throw keyword is used to explicitly throws keyword is used to declare an exception.
throw an exception.
3) Throw is used within the method. Throws is used with the method signature.
4) You cannot throw multiple exceptions. You can declare multiple exceptions.
5) Used only to throw but can not Throws is used to propagate exception to the
propagate exception to the calling calling method.
method.
6) Throw is followed by an instance. Throws is followed by class.
7) Public void m1() Public void m1() throws ArithmeticException
{ {
Throw new ArithmeticException();
} }

Built-in Exceptions
Que:
1. List any four inbuilt exceptions.
2. List four different inbuilt exceptions of Java.
Ans:
 Built-in exceptions are the exceptions which are available in Java libraries.
 Following is the list of Java Checked Exceptions:

Sr.N Exception & Description


o.

1
ArithmeticException
Arithmetic error, such as divide-by-zero.

2
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3
ArrayStoreException
Assignment to an array element of an incompatible type.

4
ClassCastException
Invalid cast.

5
IllegalArgumentException
Illegal argument used to invoke a method.
6
IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.

7
IllegalStateException
Environment or application is in incorrect state.

8
IllegalThreadStateException
Requested operation not compatible with the current thread state.

9
IndexOutOfBoundsException
Some type of index is out-of-bounds.

10
NegativeArraySizeException
Array created with a negative size.

11
NullPointerException
Invalid use of a null reference.

12
NumberFormatException
Invalid conversion of a string to a numeric format.

13
SecurityException
Attempt to violate security.

14
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.

15
UnsupportedOperationException
An unsupported operation was encountered.

Following is the list of Java UnChecked Exceptions Defined in java.lang.


Sr.No. Exception & Description

1
ClassNotFoundException
Class not found.
2
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.

3
IllegalAccessException
Access to a class is denied.

4
InstantiationException
Attempt to create an object of an abstract class or interface.

5
InterruptedException
One thread has been interrupted by another thread.

6
NoSuchFieldException
A requested field does not exist.

7
NoSuchMethodException
A requested method does not exist.

User-Defined Exception
 Java provides us facility to create our own exceptions which are basically derived classes
of Exception.
 For example:

class MyException extends Exception


{
public MyException(String msg)
{
super(msg);
}
}

class ThrowExcep
{
static void div() throws MyException
{
int a=2,b=0;
if(b==0)
throw new MyException("demo");
else
{
int ar=a/b;
}
}
public static void main(String args[])
{
try
{
div();
}
catch(MyException e)
{
System.out.println("Divide");
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy