5-Module - 5-09-10-2024
5-Module - 5-09-10-2024
Packages in JAVA
Packages in JAVA
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two
form, built-in package and user-defined
package.
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Our first package program
The keyword package is mandatory to create package programs in java
Let us now create a simple program with filename as first2.java
Let the code be as such:
package firstpack;
public class first2
{
public static void main(String a[])
{
System.out.println("this is inside first program");
}
}
How to compile java package
• Since we are not using any IDE, we have to
follow the way to compile:
Syntax:
• javac -d directory javafilename
For example
• javac -d . first2.java
• (After this you can see a folder created in the
current directory)
How to run java package program
• The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. We can use any directory name
like /home (in case of Linux), d:/abc (in case of windows) etc. If
we want to keep the package within the same directory, we can
.
use . (dot). The represents the current folder.
How to access package from another package?
// Parameterized constructor
thiskey(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
1) Checked Exception
The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Common exceptions
• 1. 50/0 Arithmetic exception
• 2. String s = null, S.o.p(s.length)
_______________________
• 3. int a[]=new int[5];
a[6] = 20; _________________
4. String s= “HELLLO”;
S.o.p(Interger.parseInt(S)); _________
Java Exception Handling Keywords
• There are 5 keywords used in java exception handling.
• try -> try block is used to enclose the code that might
throw an exception. It must be used within the method
• Catch -> Java try block must be followed by either
catch or finally block. catch block is used to handle the
Exception. multiple catch block with a single try is also
possible
• Finally-> Java finally blockis always executed whether
exception is handled or not. Java finally block follows
try or catch block.
• Throw -> 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. When
a throw statement is encountered and
executed, execution of the current method is
stopped and returned to the caller
• Throws ->Whereas the throws keyword is used
to declare that a method may throw one or
some exceptions
Syntax
java try-catch
• try{
• //code that may throw exception
• }catch(Exception_class_Name ref){}
try-finally block
• try{
• //code that may throw exception
• }finally{}
Example program for arithmetic exception
// program using exception
// program with out exception class exp1
class exp1 {
{ public static void main(String
public static void main(String ar[]) ar[])
{
{
try
int a = 50/0; {
System.out.println("the value of a int a = 50/0;
"+a); System.out.println("the value
} of a "+a);
} }catch(Exception e)
{System.out.println(e);}
System.out.println("lines of
coding continues");
How exception is handled using try-catch
Multiple catch block
class exp2
{
public static void main(String ar[])
{
try
{
String s = "helo";
int a[] = new int[5];
a[5]= Integer.parseInt(s);
} catch (NumberFormatException e )
{
System.out.println("\nNumber format:"+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("\nArray index: "+e);
}
catch(Exception e){}
System.out.println("\nprogram continues...");
}
}
Conclusions from multiple catch
1. At a time only one Exception is occured and
at a time only one catch block is executed.
2. All catch blocks must be ordered from most
specific to most general i.e. catch for
ArithmeticException must come before
catch for Exception . (Get the answer for this
conclusion)
Nested try-catch block
• Some cases where certain set of code causes
some error and another set of code causes
another error then we are in need of nested
try-catch block..(Example program exp3.java)
• class exp3
• { try
• public static void main(String ar[]) {
• int a[] = new int[5];
{
a[5]= 100;
• try }catch(ArrayIndexOutOfBoundsException
• { e)
• try {
• { System.out.println("\nArray index: "+e);
• String s = "helo"; }
• }catch(Exception e)
int a = Integer.parseInt(s);
{
• } catch (NumberFormatException System.out.println("General
e ){ exeception.....");
• System.out.println("\nNumber }
format:"+e); System.out.println("\nprogram
• } continues...");
}
}
Finally block
• Java finally block is a block that is used to
execute important code such as closing
connection, stream etc. Java finally blockis
always executed whether exception is handled
or not. Java finally block follows try or
catch block.
Finally block
• class finally2
• {
• public static void main(String args[])
• {
• try
• {
• int a[] = new int[10];
• a[23]=45;
• }
• finally
• {
• int a=10, b=0;
• int c = a/b;
• System.out.println(c);
• System.out.println("This block will execute even if the exception is present but not
• handled");
• }
• System.out.println("program continues..");
• }
• }
Try-catch inside finally block
• class finally2
• {
• public static void main(String args[])
• {
• try
• {
• int a[] = new int[10];
• a[23]=45;
• } catch(Exception e) {System.out.println(e);}
• finally
• {
• try
• {
• int a=10, b=0;
• int c = a/b;
• System.out.println(c);
• System.out.println("This block will execute even if the exception is present but not
• handled");
• }catch(Exception e){System.out.println(e);}
• }
• System.out.println("program continues..");
• }
User-defined Exception
• If you are creating your own Exception that is
known as custom exception or user-defined
exception. Java custom exceptions are used to
customize the exception according to user
need.
• //write a exception program to indicate person to pay the income tax or not
• import java.util.*;
• class Incometax extends Exception
• {
• Incometax(String s)
• {
• super(s);
• }
• }
• class userdefinedexception
• {
•
• static void check(int salary) throws Incometax
• {
• if(salary <100000)
• throw new Incometax("No need to pay tax");
• else
• System.out.println("Pay your tax");
• }
•
• public static void main(String args[])
• {
• int n;
• Scanner s = new Scanner(System.in);
• System.out.println("Enter your annual salary");
• n = s.nextInt();
• try{
• check(n);
• }catch(Exception e){System.out.println("Exception caught: "+e);}
•
• System.out.println("sucess...");
• }
Advantage of Exception Handling
• to maintain the normal flow of the
application.
• Ie. Suppose there is 6lines of coding
statements in our program and there occurs
an exception at statement 5, rest of the code
will not be executed i.e. statement 6 to 10 will
not run. If we perform exception handling,
rest of the statement will be executed. That is
why we use exception handling in java.
Practise Programs- Exception Handling
1. Write a class to sort the given set of n integers in descending order. Include a try block
to locate the array index out of bound exception and catch it.
2. Write a program to calculate the grade of a student. Enter marks for minimum 5
subjects. While entering marks if the mark is negative throw NegativeMarkException
and if the mark is greater than 100 throw OutofRangeException.
3. Write a Java Program to create a class Employee containing EmpCode, name, age,
experience. Create a constructor to initialize the data members. Create a
display( ) method to display the details. Create a check( )method to check for the
following conditions:
• Length of EmpCode should be exactly 6
• Maximum characters of name is 30
• Age cannot be less than 18 ormore than 58
• Experience cannot exceed age-18
4. Write a java program to get the age of the user, if the age of the user is less than 18, give
a message that “ you are not eligible for voting””, else allow the user to provide their
Thank you
ALL THE BEST