Session 15

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 20

Exception Handling &

Input/Output
Input in Java
• Using Scanner Class
• Using BufferedReader Class
import java.util.Scanner; // Import the Scanner class

class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String s = myObj.nextLine();
System.out.println("Username is: " + s);
}
}
import java.util.Scanner; // Import the Scanner class

class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter a number");
Int i = myObj.nextInt();
System.out.println(“Number is: " + i);
}
}
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args)
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(“Name is “+ name);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args)
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
int x=Integer.parseInt(s);
System.out.println(“Value is “+ x);
}
}
Exception Handling
• Exception is a run-time error which arises during the execution of java
program
• An exception can occur for many different reasons, including the
following-
• 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
• JVM has run out of memory
Exception Handling

• Java exception handling is managed by using five keywords: try, catch,


throw, throws and finally-
1. Try: Piece of code of your program that you want to monitor for
exceptions are contained within a try block. If an exception occurs
within the try block, it is thrown
2. Catch: Catch block can catch this exception and handle it in some
logical manner
3. Throw: System-generated exceptions are automatically thrown by
the Java run-time system. Now if we want to manually throw an
exception, we have to use the throw keyword
Exception Handling
• Throws: If a method is capable of causing an exception that it does
not handle, it must specify this behavior in the beginning so that
callers of the method can guard themselves against that exception.
We can do this by including a throws clause in the method’s
declaration. Basically, it is used for IOException. A throws clause lists
the types of exceptions that a method might throw.
• Finally: Any code that absolutely must be executed before a method
returns, is put in a finally block.
Sample Code
try
{
// Some Code Here
}
catch(Exception e1)
{
// Some Code Here
}
catch(Exception e2)
{
// Some Code Here
}
finally
{
// Some Code Here
Common Exceptions
• ArithmeticException
• Arithmetic errors- For example, divide by zero
•ArrayIndexOutOfBoundsException
•Array index is out-of-bound
•InputMismatchException
Example
import java.util.*;
public class HandleExceptionDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = scan.nextInt();
System.out.println( "The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again, Incorrect input: an integer is required)");
scan.nextLine();
}
} while (continueInput);
}}
import java.util.*;
import java.io.*;
public class IPM
{
public static void main(String[] args) {
System.out.println("Hello World");
int numer[]={4,8,16,32,64,128,256};
int denom[]={2,4,0,16,0,8};
for(int i=0; i<numer.length;i++)
{
try
{System.out.println(numer[i]/denom[i]);}
catch(ArrayIndexOutOfBoundsException e1){
System.out.println("No-Matching element found");}
catch(ArithmeticException e){
System.out.println("Cann’t divide by zero");
}
}}}
int a=100, b=50,c=50,result1;
try
{
result1= a/(b-c);
System.out.println(result1);
}
catch(ArithmeticException e2)
{
System.out.println(“divide by zero”);
}
catch(Exception e1)
{
System.out.println(“Mistake”);
}
Throw and Throws
• Throw keyword is used in the method body to throw an exception,
while throws is used in method signature to declare the exceptions
that can occur in the statements present in the method
• You can throw only one exception at a time, but you can handle
multiple exceptions by declaring them using throws keyword in the
signature itself
• If we see syntax wise than throw is followed by an instance of
Exception class and throws is followed by exception class names.
Example of throw
public class Example1
{
void checkAge(int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
Example1 obj = new Example1();
obj.checkAge(13);
System.out.println("End Of Program");
}
}
Rethrowing an Exception/ Nested-try
public class RethrowingExceptions
{
static void divide()
{
int x=6,y=0;
try
{
System.out.println(x/y);
}
catch(ArithmeticException e)
{
System.out.println("Cannot Divide by Zero in Integer Division");
throw e; // Rethrows an exception
}
}
public static void main(String[] args)
{
try
{
divide();
}
catch(ArithmeticException e2)
{
System.out.println("Rethrown Exception Caught in Main()");
e2.printStackTrace();
}
}
}
Example
public class Example1
of throws
{
int division(int a, int b) throws ArithmeticException
{
int t = a/b;
return t;
}
public static void main(String args[]){
Example1 obj = new Example1();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide number by zero");
}
}

You might also like