0% found this document useful (0 votes)
21 views36 pages

Unit-5-exception-handling

Sppu SE IT

Uploaded by

bhagwatgayal4
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
21 views36 pages

Unit-5-exception-handling

Sppu SE IT

Uploaded by

bhagwatgayal4
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 36

UNIT:5

Exception Handling
&
Generic Programming
What is an exception?
*An exception is an error condition
that changes the normal flow of
control in a program

*When an Exception occurs the


normal flow of the program is
disrupted and the
program/Application terminates
abnormally, which is not
recommended, therefore these
Why Exception
Occurs?
An exception can occur for many different
reasons, below given are some scenarios
where exception occurs.
>>A user has entered 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.
Exception Hierarchy
Exception Has two
Main classes :
1. Checked exceptions : known
as compile time exceptions.
Programmer should take care of
(handle) these exceptions

2. Unchecked exceptions :
Known as Runtime Exceptions.
These include programming bugs,
such as logic error also.
Checked
exceptions
Example
import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]){


File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}

} Output: C:\>javac FilenotFound_Demo.java


FilenotFound_Demo.java:8:
error: unreported exception
FileNotFoundException; must be caught
or declared to be thrown
FileReader fr = new FileReader(file);
exceptions
Example
public class Unchecked_Demo {

public static void main(String


args[]){
int num[]={1,2,3,4};
System.out.println(num[5]);
}

} Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException
: 5 at
Exceptions.Unchecked_Demo.main(Unchec
ked_Demo.java:8
Exception Handling
Terms
1.Try – used to enclose a segment of code that may
produce a exception

2.Catch – placed directly after the try block to


handle one or more exception types

3.Throw – to generate an exception or to describe


an instance of an exception

4.Finally – optional statement used after a try-


catch block to run a segment of code regardless if
a exception is generated
Try – Catch Block
Try – used to enclose a segment of
code that may produce a exception
Catch – placed directly after the try
block to handle one or more exception
types

try {
statements;
}
catch(Exception ex) {
perform operations before exits;
throw ex;
Multiple catch
statements
try {
<code segment that may
throw an exception..>
} catch (IOException e) {

System.out.println(e.getMessage());
} catch (FileNotFoundException e){
System.out.println(“FileNotFound!”);
}
Nested try-catch
block
try {
statement 1;
try {
statement 2;
statement 3;
}
catch(Exception e) { }
}
catch(Exception e) { }
By using Throw
THROW-generate an exception or to describe an
instance of an exception
Define a class:
public class EmptyStackException extends Exception {
}
Here is how you use the class:
public class Stack {
public Object Pop() throws EmptyStackException
{
if (Empty()) throw new EmptyStackException();
...
}
}
Note that you must use new to create an
exception object; you cannot just throw an
exception.
Example
static class Exception2{
static int sum(int num1, int num2){
if (num1 == 0)
throw new ArithmeticException("First parameter
is not valid");
else
System.out.println("Both parameters are
correct!!");
return num1+num2; }
public static void main(String args[]){
int res=sum(1,12);
System.out.println(res);
System.out.println("Continue Next statements");
}
}
The finally
try {
statements;
}
catch(TheExceptionex) {
handling ex;
}
finally {
finalStatements;
}
Example
public static void main(String[] arg){

try{
int i = 10/0;
} catch(Exception ex){
System.out.println("Inside 1st catch
Block");
} finally {
System.out.println("Inside 1st finally
block");
}

try{
int i = 10/10;
} catch(Exception ex){
System.out.println("Inside 2nd catch
Block");
} finally { Inside 1st catch Block
Inside
System.out.println("Inside 1stfinally
2nd finally block
block"); Inside 2nd finally block
Generics and Collections
Generic programming is a style of computer programming in which
algorithms are written in terms of types to-be-specified-later that are
then instantiated when needed for specific types provided as
parameters.

Generics are a facility of generic programming that were added to


the Java programming language in 2004 within version J2SE 5.0.
They were designed to extend Java's type system to allow “a type or
method to operate on objects of various types while providing
compile-time type safety”

The Java collections framework supports generics to specify the


type of objects
stored in a collection instance.
According to Java Language Specification:
1. A type variable is an unqualified identifier. Type variables are introduced by generic class
declarations, generic interface declarations, generic method declarations, and by generic
constructor declarations.
2. A class is generic if it declares one or more type variables. These type variables are known as
the type parameters of the class. It defines one or more type variables that act as parameters.
A generic class declaration defines a set of parameterized types, one for each possible
invocation of the type parameter section. All of these parameterized types share the same
class at runtime.
3. An interface is generic if it declares one or more type variables. These type variables are
known as the type parameters of the interface. It defines one or more type variables that act as
parameters. A generic interface declaration defines a set of types, one for each possible
invocation of the type parameter section. All parameterized types share the same interface at
runtime.
4. A method is generic if it declares one or more type variables. These type variables are known
as the formal type parameters of the method. The form of the formal type parameter list is
identical to a type parameter list of a class or interface.
5. A constructor can be declared as generic, independently of whether the class that the
constructor is declared in is itself generic. A constructor is generic if it declares one or more
type variables. These type variables are known as the formal type parameters of the
constructor. The form of the formal type parameter list is identical to a type parameter list of a
generic class or interface.
Consider the following example:

Although the code is compiled without error, it throws a runtime exception


(java.lang.ClassCastException) when
executing the second last statement of code. This type of problem can be avoided
by using generics
With
Generics:

Compiling this fragment with J2SE 5.0 (or later) will yield a compile-time
error because the compiler will detect that list.get(2) returns String
instead of Integer
Entry<String, String> grade = new Entry<String,
String>("Mike", "A");

Entry<String, Integer> mark = new Entry<String,

Integer>("Mike", 100); System.out.println("grade: " +

grade);
System.out.println("mark: " + mark);

Entry<Integer, Boolean> prime =


new Entry<>(13, true); //Diamond Operator

if (prime.getValue())
System.out.println(prime.getKey() + " is prime.");
else
Output: System.out.println(prime.getKey() + " is not
prime.");
grade: (Mike,
A) mark: (Mike,
100)
13 is prime.
Note: If we remove the first <Type> in the above method, we will
get compilation error (cannot find symbol 'Type') since it
represents the declaration of the symbol. In many cases the user of
the method need not indicate the type parameters, as they can
be inferred:

Entry<String, String> pair = Entry.twic e("Hello");

The parameters can be explicitly added if

needed: Entry<String, String> pair =

Entry.<String>twic e("Hello");
Output:

java.lang.Integer = 11
java.lang.String =
GeeksForGeeks
java.lang.Double = 1.0
Programs that uses Generics has got many benefits over non-generic code.

1. Code Reuse: We can write a method/class/interface once and use for any type we
want.

2. Type Safety : Generics make errors to appear compile time than at run time (It’s
always better to know problems in your code at compile time rather than making
your code fail at run time).

3. Individual Type Casting is not required

ArrayList <String> al= new ArrayList<String> ();


al.add(“Gurpreet");

// Typec asting is not needed


String s1 = al.get(0);

4. Implementing generic algorithms: By using generics, we can implement algorithms


that
work on different types of objects and at the same they are type safe too.
What is Collection in java?

 Collection represents a single unit of objects i.e. a group.

What is framework in java?


•provides readymade architecture.
•represents set of classes and interface.
•is optional.

What is Collection framework?


Collection framework represents a unified architecture for
storing and manipulating group of objects. It has:
•Interfaces and its implementations i.e. classes
•Algorithm
Java ArrayList class uses a dynamic array for storingthe elements. It
inherits
AbstractList class and implements List interface.

The important points about Java ArrayList class are:


•Java ArrayList class can contain duplicate elements.
•Java ArrayList class maintains insertion order.
•Java ArrayList class is non synchronized.
•Java ArrayList allows random access because array works at the
index basis.
•In Java ArrayList class, manipulation is slow because a lot of shifting
needs to
be occurred if any element is removed from the array list.
Java LinkedList class uses doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the AbstractList class
and implements List and Deque interfaces.

The important points about Java LinkedList are:


•Java LinkedList class can contain duplicate elements.
•Java LinkedList class maintains insertion order.
•Java LinkedList c lass is non sync hronized.
•In Java LinkedList class, manipulation is fast because no shifting
needs to
be occurred.
•Java LinkedList c lass c an be used as list, stac k or queue.
Java HashMap class implements the map interface by using a
hashtable. It
inherits AbstractMap class and implements Map interface.

The important points about Java HashMap class are:


•A HashMap contains values based on the key.
•It c ontains only unique elements.
•It may have one null key and multiple null values.
•It maintains no order.
Thanks All

You might also like