Showing posts with label Exceptions. Show all posts
Showing posts with label Exceptions. Show all posts

Simple 'Try and Catch' Example


import java.io.*;

public class TryCatchExample
{
public static void main (String args[]) throws IOException
{
BufferedReader HelloWorld = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter A Number: ");


try
{
int GalaxyNumber = Integer.parseInt(HelloWorld.readLine());
}


catch (NumberFormatException ShowError)
{
System.out.println("Enter A Number: ");
}
}

you can also have...


catch (NumberFormatException ShowError)
{
System.out.println(ShowError);
}



instead of...


catch (NumberFormatException ShowError)
{
System.out.println("Enter A Number: ");
}


... to know the error.

Try and Catch

Try - Make an attempt or effort to do something
Catch - Intercept and Hold

Syntax:

try
{
statement(s);
}

catch (Exception Handler Tag)
{
statement(s);
}


The try and catch  allows you to test a block of errors. Once it encounters a block of errors in the try, it passes it to the tag. A tag is a variable that hold the exception. The statements under the catch are to be executed once the try receives an error (it catches the errors from the try).

Exception Handler is an exception. An exception an error. Famous exceptions are IOException and NumberFormatException.

For an example of a try and catch, refer to the next post.

Extended Search

Custom Search
Hello World