You are on page 1of 4

Exceptions

On Monday 4th March,2019 at 7:30am, we had a java class at NNB3 discussing about
the idea of exceptions in java.
According to www.journaldev.com "Exception is an error event that can happen during
the execution of a program and disrupts its normal flow".Exception can arise from
different kind of situations such as wrong data entered by user, hardware failure,
network connection failure, Database server down etc. In this section, we will
learn how exceptions are handled in java.
So actually the purpose of the lecture was to educate us on the expected errors we
could have when writing a program and the ways we could handle such erros
called"Exception handling". Java Exception handling is a framework that is used to
handle runtime errors only.
Some keywords used in exception handling
1. throw:Sometime we might want to generate exception explicitly in our code, for
example in a user authentication program we should throw exception to client if the
password is null. throw keyword is used to throw exception to the runtime to handle
it.
example
public class ThrowExample {
static void checkEligibilty(int stuage, int stuweight){
if(stuage<12 && stuweight<40) {
throw new ArithmeticException("Student is not eligible for registration");

}
else {
System.out.println("Student Entry is Valid!!");
}
}

public static void main(String args[]){


System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}www.beginnersbook.com
2.Try-catch:We use try-catch block for exception handling in our code. try is the
start of the block and catch is at the end of try block to handle the exceptions.
We can have multiple catch blocks with a try and try-catch block can be nested
also. catch block requires a parameter that should be of type Exception.
Example of the Try-catch block
class Try-catch {
public static void main(String args[]) {
int num1, num2;
try {

num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {

System.out.println("You should not divide a number by zero");


}
catch (Exception e) {

System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}www.beginnersbook.com
3.Finally:finally block is optional and can be used only with try-catch block.
Since exception halts the process of execution, we might have some resources open
that will not get closed, so we can use finally block. finally block gets executed
always, whether exception occurred or not.
example
class finally
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}

finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}beginnersbook.com
you can handle a specific exception or a general exception by using the above
codes.
Array.index out of bound exception is a class in java
Array.index out of bounds exception
An array-index out of bounds exception is a Java exception thrown due to the fact
that the program is trying to access an
element at a position that is outside an array limit, hence the words "Out of
bounds". In other words, the program is trying to
access an element at an index that is outside the array bounds. To understand array
bounds, let us consider the following diagram:
An example to demonstrate the Array.inex out of bounds exception
public class OutOfBounds {

public static void main(String[]args){

int [] array = {4,8,15,16,23,42};

System.out.println("The lottery numbers are ...");


for(int i = 0; i <= array.length; i++){ // here, i<=array.length will be
true,even when i is equal to 6
//which will cause an ArrayIndexOutOfBoundsException

System.out.println(".."+array[i]);

}
}
}Source reference www.voidexception.weebly.com
example 2
public class OutOfBounds {

public static void main(String[]args){

int [][] array2D = {


{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}

System.out.println("The 1st number, 1st row = "+array2D[0][0]);


System.out.println("The 2nd number, 1st row = "+array2D[1][0]);
System.out.println("The 3rd number, 1st row = "+array2D[2][0]);
System.out.println("The 4th number, 1st row = "+array2D[3][0]);
//Beeeeeeeep! Out of bounds Exception

}
}
We also looked at how to write your code to prevent exceptions, looking at how to
handle a specific exception or a genereal exception

This is an example of program with an exception


import java.util.Scanner;
public class Exceptions {
public static void main(String []args){
int[] xValues={3,7,2,4,9};
for (int i=0; i<=xValues.length; i++){
System.out.println(xValues[i]);
}

}
}Class example
How to write your code to prevent exceptions
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionHandling {

public static void main(String[] args) throws FileNotFoundException,


IOException {
try{
testException(-5);
testException(-10);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
System.out.println("Releasing resources");
}
testException(15);
}

public static void testException(int i) throws FileNotFoundException,


IOException{
if(i < 0){
FileNotFoundException myException = new FileNotFoundException("Negative
Integer "+i);
throw myException;
}else if(i > 10){
throw new IOException("Only supported for index 0 to 10");
}

}Exeception handling of a simple code.


the above example talks about a type of exception called the file not found
exception.

Null pointer exception


NullPointerException is a RuntimeException. In Java, a special null value can be
assigned to an object reference. NullPointerException is thrown when program
attempts to use an object reference that has the null value.

These can be:

Invoking a method from a null object.


Accessing or modifying a null object�s field.
Taking the length of null, as if it were an array.
Accessing or modifying the slots of null object, as if it were an array.
Throwing null, as if it were a Throwable value.
When you try to synchronize over a null object.
An example of a program that causes null pointer exception

import java.io.*;

class GFG
{
public static void main (String[] args)
{

String ptr = null;

try
{

if (ptr.equals("gfg"))
System.out.print("Same");
else
System.out.print("Not Same");
}
catch(NullPointerException e)
{
System.out.print("NullPointerException Caught");
}
}
} www.geeksforgeeks.org

We were asked to google search for the types of exceptions and use them to write a
program
Write five programs that demonstrate five different exceptions(Assignment)

Assignment
create a file called data.txt
The quick brown fox jumps over the lazy dog.
Write a java program that reads the content of data.txt and displays the content in
the console
A class called buffered reader and file reader

You might also like