Exception Handling

keyworks
1. try
2. catch
3. finally
4. throw
5. throws

1. try-catch-finally
package org.vit.java.exception;

import java.util.Scanner;

public class Divison
{

public static void main(String[] args) throws OwnException
{
Scanner in = new Scanner(System.in);
System.out.println(“Enter the First Number:”);
int x =in.nextInt();

System.out.println(“Enter the First Number:”);
int y = in.nextInt();
float z = 0;

try
{
z = x / y;
System.out.print(“The Divison value is” +z);

}
catch(ArithmeticException a)
{
System.out.println(a.toString());
}
finally
{
System.out.print(“I am always here”);
}

}

}

package org.vit.java.exception;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Sample {

public void getFile(String name)
{
try
{
FileInputStream f = new FileInputStream(new File(name));

}
catch (FileNotFoundException e)
{

System.out.print(e.toString());
}
}
public static void main(String[] args)
{
Sample s = new Sample();
s.getFile(“ss.txt”);
}

}

2. Creating User Defined Exception

package org.vit.java.exception;

import java.util.Scanner;

class MyException extends Exception
{
public String toString()
{
return “Number is less than 10″;
}
}

public class MyExceptionTest
{

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println(“Enter the First Number:”);
int x =in.nextInt();

System.out.println(“Enter the First Number:”);
int y = in.nextInt();
float z = 0;

try
{
z = x / y;
if(z < 10.0)
{
throw new MyException();
}
}
catch (MyException e)
{
System.out.println(e.toString());
}
catch(ArithmeticException a)
{
System.out.println(a.toString());
}
finally
{
System.out.print(“The Divison value is” +z);
}
}
}

3. Throws Example

package org.vit.java.exception;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Sample {

public void getFile(String name) throws FileNotFoundException
{

FileInputStream f = new FileInputStream(new File(name));

}
public static void main(String[] args) throws FileNotFoundException
{
Sample s = new Sample();
s.getFile(“ss.txt”);
}

}

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Spam protection by WP Captcha-Free