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

Lec 12

Uploaded by

Ahmed Mehmood
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lec 12

Uploaded by

Ahmed Mehmood
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Object Oriented Programming

Lecture 12
Java – Packages, Exceptions
Handling

1
Java – Packages
• Packages are used in Java in order to prevent
naming conflicts, to control access, to make
searching/locating and usage of classes etc.
• A Package can be defined as a grouping of related
types(classes, interfaces and annotations )
providing access protection and name space
management.
• Some of the existing packages in Java are::
– java.lang - bundles the fundamental classes
– java.io - classes for input , output functions are
bundled in this package
2
Package Example

EXAMPLE 1:
package animals;
interface Animal {
public void eat();
public void travel();
}

3
import Keyword
• If a class wants to use another class in the
same package, the package name does not
need to be used. Classes in the same package
find each other without any special syntax
• Following techniques for referring to a class in
a different package
– packagename.classname;
– import packagename.classname;
– import packagename.*;

4
Java - Exceptions
• Any unexpected or unwanted event that will
disturbs the normal flow or execution of a
program is called Exception. An exception can
occur for many different reasons, e.g.
– 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.
– 1/0
– etc

5
Exceptions Handling
• If any of the Exception occur and we could
find out some alternative way that will not
disturbs the normal execution of program is
called Exceptions Handling.
• Exceptions Handling doesn’t mean to remove
exceptions or errors but it is something to find
an alternative way for program execution.

6
Difference between Exception & Error

7
Exception Hierarchy:
• All exception classes are subtypes of the
java.lang.Exception class.
• The exception class is a subclass of the
Throwable class.
• Other than the exception class there is
another subclass called Error which is derived
from the Throwable class.

8
Exception Hierarchy:

9
Hierarchy of Exception Class

10
Categories of Exceptions
• Checked exceptions:
– A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. For example, if a file is to be opened, but
the file cannot be found. These exceptions cannot simply be ignored at the time of
compilation.

• Runtime exceptions:
– A runtime exception is an exception that occurs that probably could have been
avoided by the programmer. As opposed to checked exceptions, runtime exceptions
are ignored at the time of compilation. E.g anything divided by 0 will give arithmetic
exception.

• Errors:
– These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error
will arise or exception occurs or memory is not enough to run the program. They are
also ignored at the time of compilation.

11
Try-catch block
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

12
Example 1
public class Main
{
public static void main(String[ ] args)
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); //
error! }
}
Output
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException:
10
at Main.main(Main.java:4)
Example 2
public class Main
{
public static void main(String[ ] args)
{
try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e) {
System.out.println("Something went wrong.");
}}}
Output
Something went wrong.
Example
import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
} 17
Output
Exception
thrown :java.lang.ArrayIndexOutOfBoundsExc
eption: Index 3 out of bounds for length 2 Out
of the block
Finally

The finally statement lets you execute code,


after try...catch, regardless of the result:
A finally block contains all the crucial
statements that must be executed whether
exception occurs or not. The statements
present in this block will always execute
regardless of whether exception occurs in try
block or not.
Example 3
public class Main
{
public static void main(String[] args)
{
try
{
int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]);
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
finally { System.out.println("The 'try catch' is finished.");
}}}
Output
Something went wrong.
The 'try catch' is finished.
The finally Keyword

public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
22
}
Output
Exception
thrown :java.lang.ArrayIndexOutOfBoundsExc
eption: Index 3 out of bounds for length 2 First
element value: 6 The finally statement is
executed
The throw keyword

• The throw statement allows you to create a


custom error.
• The throw statement is used together with
an exception type. There are many exception
types available in
Java: ArithmeticException, FileNotFoundExcep
tion, ArrayIndexOutOfBoundsException, Securi
tyException, etc:
Example 4
public class Main
{
static void checkAge(int age) {
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!"); } }
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 18...)
}}
Output
Exception in thread "main"
java.lang.ArithmeticException: Access denied -
You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
Contd.
If age was 20, you would not get an exception:
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
Exercise:

Insert the missing parts to handle the error in


the code below.
_______{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} ___________(Exception e)
{ System.out.println("Something went
wrong."); }
Thank You

29

You might also like