Create exception handling


In this post, i want to share with you about how to create our own exception handling. Sometime when we build our program, we want it to handle certain mistake or exception that not exist in java predefined exception class.For example we want to control user from put negative integer value. Complete source code below will show you, how you can create an exception class that avoid user from put negative integer value.

*************************************************************
COMPLETE SOURCE CODE FOR : NegativeIntegerException.java
*************************************************************


import java.util.Scanner;

public class NegativeIntegerException extends RuntimeException
{
public void checkNumber(int a)
{
if(a<0)
{
throw new NegativeIntegerException();
}
}

public static void main(String[]args)
{
Scanner scanUserInput=new Scanner(System.in);
NegativeIntegerException nie=new NegativeIntegerException();
boolean b=true;
while(b)
{
System.out.println("Put an integer");
System.out.println("Put 0 EXIT");
int c=scanUserInput.nextInt();
if(c==0)
{
b=false;
}
else
{
try
{
nie.checkNumber(c);
System.out.println("YOUR NUMBER IS : "+c);
}
catch(NegativeIntegerException exception)
{
System.out.println("<<PLEASE PUT ONLY POSITIVE INTEGER!!!>>");
}
}
}
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************

Java exception handling


Now, i want to share with you about exception handling in java. Okay, this is only for introduction to exception handling. Firstly, what is exception?

Exception - a person or thing that is excepted or that does not follow a rule.

So, if we talk about exception handling in java program, it mean we want to handle any mistake that we can handle during compile time or runtime.

For example :
-User put String into input field that only handle integer value.
-Out of memory.
-Array index that over than it's (length-1) or negative value. We also called it as ArrayIndexOutOfBoundsException

Why, i said "we want to handle any mistake that we can handle"?The answer is, there exist error that we can't handle.

For example :
-Blue screen of death(BSOD)
-Computer suddenly crash
-Black out
-Or someone switch off your computer

Ok, i hope you understand what i mean until this line. Why we need exception handling ? The answer is, we want to make sure our program is robust. It will try to handle any mistake that the user make.

Now, we will see two sample java programs. Both of them will ask user to input their age.After that, it will print it's value. This program only terminate when user put 0. Like we know, age is integer value. It can't be floating point number or String except your program need the user to put it in String. It is make not sense if when you ask someone for their age, and after that it answer like this "MY AGE IS 19.28". First program will has no exception handling. It will print some description about exception that occur and after that the program will end without follow program flow when the user put String value or others. But, in second program, it totally different. It will tell user that the input is wrong. After that, it will ask again until user put 0 to exit.Let we see both of them.Before i forget, if you put negative integer value, this program will work fine because it also integer. I will discuss later, about how to handle this in how to create our own exception handling.

FIRST PROGRAM :

import java.util.Scanner;

public class Test
{
public static void main(String[]args)
{
while(true)
{
Scanner scanUserInput=new Scanner(System.in);
System.out.println("Put 0 to exit");
System.out.println("What is your age ?");
int a=scanUserInput.nextInt();
if(a==0)
{
System.exit(0);
}
System.out.println("YOUR AGE IS : "+a);
}
}
}


SECOND PROGRAM :

import java.util.Scanner;
import java.util.InputMismatchException;

public class Test
{
public static void main(String[]args)
{
while(true)
{
try
{
Scanner scanUserInput=new Scanner(System.in);
System.out.println("Put 0 to exit");
System.out.println("What is your age ?");
int a=scanUserInput.nextInt();
if(a==0)
{
System.exit(0);
}
System.out.println("YOUR AGE IS : "+a);
}
catch(InputMismatchException exception)
{
System.out.println("Hey, don't play with me!");
System.out.println("PLEASE PUT ONLY INTEGER VALUE");
}
}
}
}


Java modal window


Hi everyone, today i want to share with you about MODAL WINDOW.How it's look like? Before i show you example of MODAL WINDOW, let we look for it's little description :

If a window is modal, no other window can be active while the modal window is displayed.

Simple example is message box from JOptionPane. When a message box is showing, you can't work with other window until you press OK or others button on the message box.
This message box is a simple example of MODAL WINDOW.

You can try compile java code below to see how it's look like.

***********************************************************
COMPLETE SOURCE CODE FOR : ModalWindow.java
***********************************************************


import javax.swing.JFrame;

import javax.swing.JOptionPane;

public class ModalWindow
{
public static void main(String[]args)
{
JFrame myWindow=new JFrame("My Window");

myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(400,400);
myWindow.setVisible(true);

JOptionPane.showMessageDialog(null,"Hello");
}
}


***********************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************

Java validate integer user input


Sometime, when we play with user input, we want to validate the input value is specific to certain data type. For example, you have a simple java program that query for user's age. Like we know age is in integer data type. So how to handle if a user put his age something like this, "fifty" or 50.34. This is impossible right? But if the user want to test the robustness of your system from error handling view, this is not impossible.Now i want to share with you, how you can handle this in a simple java program that run through command prompt.The basic idea is, if a user put other than integer value, our program will throw an exception. So, we will put our code that tell user what he/she do is wrong in the exception block.In other tutorial, i will share with you how to create your own exception handling.

***************************************************************
COMPLETE SOURCE CODE FOR : ValidateIntegerInput.java
***************************************************************


import java.util.Scanner;
import java.util.InputMismatchException;

public class ValidateIntegerInput
{
public static void main(String[]args)
{
boolean benchmark=true;
while(benchmark)
{
Scanner a=new Scanner(System.in);

try
{
System.out.println("Put 0 to exit");
System.out.println("What is your age?");

//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int b=a.nextInt();
if(b==0)
{
benchmark=false;
}
else
{
System.out.println("Your age is : "+b);
}
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("Please put integer value");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
}


***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************

Java determine drive pathname


Complete source code below will show you how to determine a pathname is a pathname for drive or not.

*********************************************************************
COMPLETE SOURCE CODE FOR : PathnameIsDrive.java
*********************************************************************


import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

import java.io.File;

public class PathnameIsDrive
{
public static void main(String[]args)
{
//Create file instance from pathname
//Try change to pathname that match any drive in your computer
//For example C:\\ for C drive.
File myFile=new File("C:\\");

//Check whether the given pathname is drive or not
if(FileSystemView.getFileSystemView().isDrive(myFile))
{
System.out.println("This is a drive");
}
else
{
System.out.println("This is not a drive");
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java and pathname

Before i go through about file's operation, i want to share with you about "pathname" keyword. In java there has lot of methods play with pathname.

For example :
When we want to create a file instance like below
******************************************
File myFile=new File("c:\\mytext.txt");
******************************************

"c:\\mytext.txt" is a pathname for mytext.txt that locate in c drive.Origin for c:\\mytext.txt is c:\mytext.txt.We use two backslash to prevent syntax error when we compile it.

So, what is pathname ?
  • A pathname is a string that describes what directory the file is in, as well as the name of the file.

Java open cd tray in Windows XP


Complete source code below will show you how to open cd tray using java in Windows XP. I'm not sure whether this code success or not in Vista. I hope someone that use Vista will tell me through comment. It is simple. We will use VBScript code to open cd tray for us. Before i forget, VBScript that will use is VBScript that has related to WSH(Windows Script Host). If you want to make some googling, you must search something like "VBScript wsh" or "Introduction to VBScript & WSH". This is because, if you use only something like "VBScript", you will be bring to page that explain about VBScript in web page development. For someone that interesting in computer virus development, you can try to learn VBScript in wsh. Most of computer virus today is writing using this stuff beside using c,c++,assembly language or others.

PROBLEM IN THIS CODE : How to terminate wscript.exe that left in process tab in windows task manager. Tell me if you know how to solve it in comment box.

*************************************************************
COMPLETE SOURCE CODE FOR : OpenCdTray.java
*************************************************************


import java.awt.Desktop;

import java.io.File;
import java.io.PrintWriter;

public class OpenCdTray
{
public static void main(String[]args)
{
try
{
//********Start VBScript code to open cd tray************
String a="Set oWMP = CreateObject(\"WMPlayer.OCX\")"+"\n"
+"Set colCDROMs = oWMP.cdromCollection"+"\n"
+"For d = 0 to colCDROMs.Count - 1"+"\n"
+"colCDROMs.Item(d).Eject"+"\n"
+"Next"+"\n"
+"set owmp = nothing"+"\n"
+"set colCDROMs = nothing"+"\n"
+"wscript.Quit(0)";
//********End VBScript code to open cd tray************

//Create a vbscript file called OpenCdTray.vbs
File myCdTrayOpener=new File("OpenCdTray.vbs");

//Create a PrintWriter object that will use to write into created file
PrintWriter pw=new PrintWriter(myCdTrayOpener);

//Write all string in (a) into created file
pw.print(a);

//Flush all resource in PrintWriter to make sure
//there are no data left in this stream.
pw.flush();

//Close PrintWriter and releases any
//system resources associated with it
pw.close();

//Create a Desktop object to open created vbs file(OpenCdTray.vbs).
//It will open using default application that will use
//to handle this file in targeted computer.
//True application to run this file is wscript.exe
Desktop.getDesktop().open(myCdTrayOpener);

//Delete created vbs file before terminate application
myCdTrayOpener.deleteOnExit();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************

Call jar file from a java program


Complete source code below will show you, how to open or call a jar file (java executable file) from a java program.

Download MyJarFile.jar that will use in this tutorial.Place this file at the same location with java file below before compile and execute it.

*********************************************************************
COMPLETE SOURCE CODE FOR : CallJarFile.java
*********************************************************************


import java.awt.Desktop;

import java.io.File;

public class CallJarFile
{
public static void main(String[]args)
{
try
{
//Call MyJarFile.jar
Desktop.getDesktop().open(new File("MyJarFile.jar"));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Set JTextField selection color

Complete source code below will show you how to set JTextField selection color.

***************************************************************
COMPLETE SOURCE CODE FOR : SetJTextFieldSelectionColor.java
***************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJTextFieldSelectionColor
{
public static void main(String[]args)
{
JTextField jtf=new JTextField("Select this text");

//Color that will use as JTextField's selection color
//It is base on RGB value
//Red=255
//Green=0
//Blue=0
//You can use color picker at above to get RGB value
Color selectionColor=new Color(255,0,0);

//Set JTextField selection color
jtf.setSelectionColor(selectionColor);

JFrame myWindow=new JFrame("Set JTextField selection color");

myWindow.add(jtf);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(400,50);
myWindow.setLocationRelativeTo(null);
myWindow.setVisible(true);
}
}


***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************

Set JTextField caret color

Complete source code below will show you, how to set JTextField caret color.

****************************************************************
COMPLETE SOURCE CODE FOR : SetJTextFieldCaretColor.java
****************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJTextFieldCaretColor
{
public static void main(String[]args)
{
JTextField jtf=new JTextField(20);
jtf.setFont(new Font("Verdana",Font.BOLD,34));

JFrame myFrame=new JFrame("Set JTextField caret color");

//Set caret color base on RGB value
//R=255
//G=0
//B=0
//You can get RGB value from color picker at above
jtf.setCaretColor(new Color(255,0,0));

myFrame.setLayout(new FlowLayout());
myFrame.add(jtf);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
}
}


****************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************

RELAXING NATURE VIDEO