0% found this document useful (0 votes)
6 views17 pages

Exception Handling

exception handling for beginners
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

Exception Handling

exception handling for beginners
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Exception Handling

Runtime error is called exception

public static void main(String[] args) {

/*Exception Handling

* Runtime error is called exception.

* */

Scanner input=new Scanner(System.in);

int a=input.nextInt();

int b=input.nextInt();

System.out.println(a/b);//if the user gives zero error will occur

//new ArtihmeticException() with the message

//divide by zero and it throws the exception and it terminate


the

//program abnormally

System.out.println("Success");

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int a = input.nextInt();

int b = input.nextInt();

/*

*Exception Handler

*1. enclose the statements with in try which will monitor the
*code if any error occur it creates Object and throws

*2. Handle the exception in catch

*/

try {

System.out.println(a / b);

}catch(ArithmeticException e) {

//exception handler code

System.out.println("Enter non zero for b");

b=input.nextInt();

System.out.println(a/b);

System.out.println("Success");

/*

* Unchecked Exception

* 1.Arithmetic

* 2.indexouofbounds

* 3.InputMismatch

* 4.NumberFormat

* 5.Null pointer

*/

Scanner input=new Scanner(System.in);

//int a=Integer.parseInt(input.nextLine());//NumberFormat

a=input.nextInt();//Inputmismatch

*******************************************************************

Scanner input=new Scanner(System.in);


//int a=Integer.parseInt(input.nextLine());//NumberFormat

a=input.nextInt();//Inputmismatch

/*

* Unchecked Exception

* As a developer should handle the exception properly

* 1.Arithmetic

* 2.indexouofbounds

* 3.InputMismatch

* 4.NumberFormat

* 5.Null pointer

* Checked exception

* 1.parse exception

* 2.SqlException

* 3.FilenotFound

*/

1.try{

* if error occur go to catch

* }catch(){

*}

* 2.try{

* after completing try execute finally

* }finally{

*}

* 3.try{

* if error execute catch and finally

* if no error execute try and finally

* }catch{
* }finally{

*}

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int a[];

int n;

try {

n = input.nextInt();

a = new int[n];

for (int i = 0; i <= a.length; i++) {

a[i] = input.nextInt();

} catch (InputMismatchException e1) {

System.out.println("Invalid input");

} catch (ArrayIndexOutOfBoundsException e2) {

System.out.println("index not in the range");

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int a[];

int n;

try {

n = input.nextInt();

if(n<0)
throw new Exception();

} catch(Exception e) {

System.out.println(e);

package sample;

//uncheked ex RuntimeException

public class InvalidAge extends Exception{//for checked

InvalidAge(String msg){

super(msg);

package sample;

import java.util.Comparator;

import java.util.InputMismatchException;

import java.util.Scanner;

import java.util.Set;

import java.util.TreeSet;

public class Main {

public static void main(String[] args) {

int age=12;
if(age>=25) {

throw new InvalidAge("Invalid age");

package sample;

//uncheked ex RuntimeException

public class InvalidAge extends RuntimeException{//for checked

InvalidAge(String msg){

super(msg);

package sample;

public class Country {

private String countryCode;

private String countryName;

public Country(String countryCode, String countryName) {

super();

this.countryCode = countryCode;

this.countryName = countryName;

public String getCountryCode() {

return countryCode;

}
public void setCountryCode(String countryCode) {

this.countryCode = countryCode;

public String getCountryName() {

return countryName;

public void setCountryName(String countryName) {

this.countryName = countryName;

@Override

public String toString() {

return "Country [countryCode=" + countryCode + ",


countryName=" + countryName + "]";

package sample;

import java.util.ArrayList;

import java.util.List;

public class CountryDao {

private List<Country> countryList=new ArrayList<Country>();

public void addCountry(Country country) throws


InvalidCountryException {

if(country.getCountryName().matches("[a-zA-Z ]{1,}"))
countryList.add(country);

else

throw new InvalidCountryException("Country should


have only alphabets");

public List<Country> getCountryList() {

return countryList;

package sample;

public class InvalidCountryException extends Exception{

InvalidCountryException(String msg){

super(msg);

package sample;

import java.util.Comparator;

import java.util.InputMismatchException;

import java.util.Scanner;

import java.util.Set;

import java.util.TreeSet;

public class Main {


public static void main(String[] args) {

CountryDao countryDao=new CountryDao();

Country country=new Country("c001","nbn");

try {

countryDao.addCountry(country);

System.out.println(countryDao.getCountryList());

} catch (InvalidCountryException e) {

// TODO Auto-generated catch block

System.out.println(e);

package sample;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Comparator;

import java.util.Date;

import java.util.InputMismatchException;

import java.util.Scanner;
import java.util.Set;

import java.util.TreeSet;

public class Main {

public static void main(String[] args) {

/*

* Sample Input

* 12/12/2020

* Output

* 2020-12-12

* Sample Input

* asas

* Invalid date

* 78/78/9087

* Invalid date

*/

Scanner input=new Scanner(System.in);

String inputDate=input.nextLine();

Date date=new Date();

if(inputDate.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {

SimpleDateFormat sdf=new
SimpleDateFormat("dd/MM/yyyy");

sdf.setLenient(false);

try {

date=sdf.parse(inputDate);

sdf=new SimpleDateFormat("dd-MM-yyyy");

System.out.println(sdf.format(date));
} catch (ParseException e) {

System.out.println("Invalid Date");

}else{

System.out.println("Invalid Date");

public static void main(String[] args) {

String str="aAekjiimnbohu";

/*

*5

*/

str=str.toLowerCase();

str=str.replaceAll("[^aeiou]", "");

Map<Character,Integer> hm=

new LinkedHashMap<Character,Integer>();

for (int i = 0; i < str.length(); i++) {

char c=str.charAt(i);

if(hm.containsKey(c)) {

int cnt=hm.get(c);

cnt++;

hm.put(c, cnt);

}else {

hm.put(c, 1);

}
}

System.out.println(hm);

package sample;

import java.io.FileNotFoundException;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Comparator;

import java.util.Date;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Scanner;

import java.util.Set;

class Main{

public static void main(String[] args) throws


FileNotFoundException {

Scanner input=new Scanner(

new java.io.File("D:\\capgtutorial\\tutorial\\src\\
sample\\inputfile.txt"));

while(input.hasNextLine()) {

String s=input.nextLine();

if(s.toLowerCase().replaceAll("[^aeiou]",
"").length()==2)

System.out.println(s);
}

package sample;

import java.time.LocalDate;

import java.time.ZoneId;

import java.util.Date;

public class LocalDateToDateExample {

public static void main(String[] args) {

// Step 1: Create a LocalDate

LocalDate localDate = LocalDate.now();

// Step 2: Convert LocalDate to Date

Date date = Date.from(

localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

// Output

System.out.println("LocalDate: " + localDate);

System.out.println("Date: " + date);

Layerd Architecture

I need to create Application to store Country details into database.

To perform CRUD

1. Value Object class


Will hold the details of Country
Use to transfer data from one layer to another
package sample;
public class Country {

private String countryCode;


private String countryName;
public Country(String countryCode, String countryName) {
super();
this.countryCode = countryCode;
this.countryName = countryName;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
@Override
public String toString() {
return "Country [countryCode=" + countryCode + ",
countryName=" + countryName + "]";
}

2. DAO Data Access Object class


1. To hold the object details create array/list/set/map
2. Create functions to perform crud

package sample;

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Collectors;
public class CountryDao {

private List<Country> countryList = new ArrayList<Country>();

public void addCountry(Country country) throws


InvalidCountryException {

if (country.getCountryName().matches("[a-zA-Z ]{1,}"))

countryList.add(country);

else

throw new InvalidCountryException("Country should


have only alphabets");

public List<Country> getCountryList() {

return countryList;

public Country getCountry(String name) {

return countryList.stream()

.filter(c->c.getCountryName().equals(name))

.collect(Collectors.toList()).get(0);

3.Service Layer

package sample;

import java.util.List;

public class CountryService {


CountryDao cdao=new CountryDao();;

public void addCountry(Country country) throws


InvalidCountryException {

if(country.getCountryName().matches("[a-zA-Z ]{1,}")) {

cdao.addCountry(country);

public List<Country> getCountry(){

return cdao.getCountryList();

We can do all validation

4.Presentation Layer

package sample;

public class Main1 {

public static void main(String[] args) {

Country country=new Country("C001","India");

CountryService countryService=new CountryService();

try {

countryService.addCountry(country);

country=new Country("C002","Russia");

countryService.addCountry(country);

System.out.println(countryService.getCountry());

} catch (InvalidCountryException e) {
// TODO Auto-generated catch block

e.printStackTrace();

You might also like