Professional Documents
Culture Documents
A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Types of error:
Compile time error
Compile time error is any type of error that prevent a java program compile like a syntax error, a class not found, a bad file name for the defined
class, and so on.
Run time error
A runtime error means an error which happens, while the program is running. To deal with this kind of errors java define Exceptions. Exceptions
are objects represents an abnormal condition in the flow of the program. It can be either checked or unchecked.
1.2 Types of exception
Checked Exceptions
Errors
Runtime Exceptions
Checked Exception( handled at compile time.)
Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc. The Exception problem
can be overcome by implementing Try-Catch block.
Error
Virtual machine error: class not found, out of memory, no such method, illegal access to private field, etc
Runtime Exception(Unchecked Exception)
Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc.
The Compiler never checks the Unchecked exception during the program compilation. For example, Dividing any number by zero is an unchecked
exception.
1.3Exception Hierarchy
1.4 Exception management
Exception can be managed through five keywords in java
1.try
2.catch
3.finally
4.throw
5.throws
try-used to keep the code that going to throw error
catch-used to catch and process the error thrown by try block
example for try /catch block:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Sam
{
public static void main(String args[])
{
int k=0;
int msg;
String s1=args[0];
String s2=args[1];
int i=Integer.parseInt(s1);
int j=Integer.parseInt(s2);
try
{
k=i/j;
System.out.println(k);
}
catch(Exception e)
{
System.out.println(error);
}
}
finally-A finally block of code always executes, whether or not an exception has occurred. Finally used for avoid resource leakage .
The finally clause is executed after a try-catch block has been executed
?
1
2
3
4
5
6
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
7
8
9
10
11
12
13
14
15
16
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
1 the method
?
1
2
3
4
5
6
7
try {
// execute a query
} catch (SQLException e) {
// handles the exception, dispalying a message, whatever
} finally {
conn.close();
}
22
23
24
Primarykey
This tutorial explains how to set a primary key for a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. If we wants to change a column constrain to primary key using java use this tutorial
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
5
6
7
8
9
10
11
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
12
13
14
15
16
17
Connection conn=null;
18
19
try {
20
Class.forName(Driver).newInstance();
21
conn = DriverManager.getConnection(url,
22 uName, pwd);
Statement stmt = conn.createStatement();
23
24
25
26
27
stmt.executeUpdate(sql);
System.out.println("primarykey added
sucessfully");
28
} catch (ClassNotFoundException e) {
29
30
e.printStackTrace();
31
}
32
catch (SQLException e) {
33
34
e.printStackTrace();
35
36
catch (Exception e) {
37
38
e.printStackTrace();
39
40
finally{
try {
41
conn.close();
42
} catch (SQLException e) {
43
44
e.printStackTrace();
45
}
46
47
48
49
50
51 }
Output:
Unique statement:
This tutorial explains how to update a column constrainto unique in a table in mysql using java statement example, Load the mysql driver using
Class.forName method and create a connection to communicate with mysql database and then create a statement object to send and receive
from java code and use executeUpdate to execute the query.
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
6
7
8
9
10
11
12
13
14
15
16
17
Connection conn=null;
18
19
try {
20
Class.forName(Driver).newInstance();
21
22
23 varchar(5),city varchar(25),Unique(roll_no))";
24
stmt.executeUpdate(sql);
25
26
27
} catch (ClassNotFoundException e) {
28
29
e.printStackTrace();
30
31
}
catch (SQLException e) {
// TODO Auto-generated catch block
32
e.printStackTrace();
33
34
}
catch (Exception e) {
35
36
37
38
39
e.printStackTrace();
}
finally{
try {
40
41
conn.close();
} catch (SQLException e) {
42
43
e.printStackTrace();
44
45
46
47
48
49
50 }
51
Output:
Create statement:
This tutorial explains how to Create a table in mysql using java statement example, Load the mysql driver using Class.forName method and create
a connection to communicate with mysql database and then create a statement object to send and receive from java code
and use
executeUpdate to execute the query . The following codes in this java tutorial explain how to Create a table named staff with columns as Fields,
Type, Null, Key, Default, Extra .
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try {
Class.forName(Driver).newInstance();
20
21
22
24
System.out.println("CreateTable sucessfully");
25
26
27
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
28
29
30
e.printStackTrace();
}
catch (SQLException e) {
31
32
e.printStackTrace();
33
34
catch (Exception e) {
35
36
e.printStackTrace();
37
38
finally{
39
40
try {
41
conn.close();
42
} catch (SQLException e) {
43
44
e.printStackTrace();
}
45
}
46
47
}
48
49
50
51
Output:
Delete statement:
This tutorial explains how to delete a single row from a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. If user wants to delete a one or more rows from a table delete query will helps us to do it. Suppose if we
want to delete the details of ravi from student table we can use this sample code to delete it.
create table:
?
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
6
7
8
9
10
11
12
13
14
15
16
17
Connection conn=null;
18
19
20
try {
Class.forName(Driver).newInstance();
conn = DriverManager.getConnection(url,
21 uName, pwd);
Statement stmt = conn.createStatement();
22
23
24
25
26
stmt.executeUpdate(sql);
System.out.println("Data deleted
sucessfully");
27
} catch (ClassNotFoundException e) {
28
29
e.printStackTrace();
30
}
31
catch (SQLException e) {
32
33
e.printStackTrace();
34
35
catch (Exception e) {
36
37
e.printStackTrace();
38
39
finally{
try {
40
conn.close();
41
} catch (SQLException e) {
42
43
e.printStackTrace();
44
}
45
46
47
48
49
50
}
51
OUTPUT:
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
5
6
7
8
9
10
11
12
13
14
15
16
Connection conn=null;
17
18
try {
19
Class.forName(Driver).newInstance();
20
conn = DriverManager.getConnection(url,
21
22
23
24
uName, pwd);
Statement st= conn.createStatement();
String sql="insert into student
values('101','suresh','cse','chennai')";
st.executeUpdate(sql);
System.out.println("Data Inserted
25 sucessfully");
26
27
} catch (ClassNotFoundException e) {
28
29
e.printStackTrace();
30
31
catch (SQLException e) {
32
33
e.printStackTrace();
34
35
catch (Exception e) {
36
37
e.printStackTrace();
38
39
finally{
try {
40
conn.close();
41
} catch (SQLException e) {
42
43
e.printStackTrace();
44
}
45
46
47
48
49
50
OUTPUT:
Alter statement:
This tutorial explains how to alter a table in mysql using java statement example, Load the mysql driver using Class.forName method and create a
connection to communicate with mysql database and then create a statement object to send and receive from java code and use executeUpdate
to execute the query . While creating student table there is only four columns namely Roll_NO, Name, Department, Address. The following codes
in this java tutorial explain how to alter a table and create a new column.
create table:
?
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try {
20
Class.forName(Driver).newInstance();
21
22
conn = DriverManager.getConnection(url,
uName, pwd);
Statement stmt = conn.createStatement();
23
24 Date_of_birth date";
stmt.executeUpdate(sql);
25
26
System.out.println("table Alter
sucessfully");
27
28
} catch (ClassNotFoundException e) {
29
30
e.printStackTrace();
31
32
catch (SQLException e) {
33
// TODO Auto-generated catch block
34
e.printStackTrace();
35
36
catch (Exception e) {
37
38
e.printStackTrace();
39
40
finally{
41
try {
conn.close();
42
} catch (SQLException e) {
43
44
e.printStackTrace();
45
}
46
47
48
}
}
}
49
OUTPUT:
Update statement:
This tutorial explains how to update a existing row in a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. Use update query to update a existing data in a table this will be helpful in modifying record in a table.
create table:
?
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
6
7
8
9
10
11
12
13
14
15
16
17
Connection conn=null;
18
19
try {
Class.forName(Driver).newInstance();
20
21
22
24
stmt.executeUpdate(sql);
25
26
27
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
28
e.printStackTrace();
29
30
}
catch (SQLException e) {
31
32
33
34
e.printStackTrace();
}
catch (Exception e) {
35
36
e.printStackTrace();
37
38
finally{
39
try {
40
41
conn.close();
42
} catch (SQLException e) {
43
44
e.printStackTrace();
45
}
}
46
47
}
48
49
50
51
OUTPUT:
Select statement:
This tutorial explains how to fetch or retrieve all row in a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeQuery to execute the query and use a resultset object to hold the data as java object. If we wants to add a new record into the table
or to add a new row, just use this following code to update the table with new record.
create table:
?
2
3 Department varchar(7),Address varchar(30));
4
5 Query OK, 0 rows affected (0.06 sec)
Input:
Java code:
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
6
7
8
9
10
/**
* @param args
*/
11
12
13
14
15
16
17
18
Connection conn=null;
19
20
try {
Class.forName(Driver).newInstance();
21
22
conn = DriverManager.getConnection(url,
uName, pwd);
23
24
25
26 sucessfully used");
27
while (rs.next()) {
28
String Roll_no=
rs.getString("Roll_no");
29
30
String department=
31 rs.getString("department");
32
String address=
rs.getString("address");
33
System.out.print(Roll_no+ "\t");
34
System.out.print(name+ "\t");
35
System.out.print(department+ "\t");
36
37
38
} catch (ClassNotFoundException e) {
39
40
e.printStackTrace();
41
42
catch (SQLException e) {
// TODO Auto-generated catch block
43
e.printStackTrace();
44
45
catch (Exception e) {
46
47
48
e.printStackTrace();
}
49
finally{
50
try {
51
conn.close();
52
} catch (SQLException e) {
53
54
e.printStackTrace();
55
56
57
58
59
60 }
OUTPUT:
select statement sucessfully used:
101 suresh
103 arivu
104 muthu
cse dharmapuri
AE
trichy
ECE ariyalur
105 mani
EEE kovai
106 tamil
CSE trichy
107 Raja
IT
tanjur
1
2
3
4
/**
* @author
candidjava
5
6
import java.io.File;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
10 import java.io.IOException;
11
12 public class ReadFileUsingBufferedInputStream {
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
try {
29
if (bin != null)
30
bin.close();
31
32
33
34
}
35
}
36
}
Output
class A
{
{
System.out.print(Init);
}
Static
{
System.out.print(Static);
}
A()
{
System.out.print(Constructor);
}
}
/**
@author: candidjava
4
5
6
*/
public class DeeValueOfStringLong
{
9
10
11
try{
String s="candid";//get the string
Long l=new Long(246);//get the long value
System.out.println(l.valueOf(s));// to return a long object
15
16
17
{
System.out.println(e.getMessage());//print the message
}
18 }
19 }
output:
For input string: candid
/**
@author: candidjava
@description: valueOf(String s,int radix) is return a Long object holding the value
by the string argument in the specified radix.
4
5
*/
public class DeeValueOfStringRadixLong
try{
12
13
14
}
catch(Exception e)//if any exception occurs means catch exception
{
/**
@author: candidjava
@description: valueOf(String s,int radix) this method is used to a Short object hold
represented by the string argument in the specified radix.
4
5
*/
public class ShortValueOf extends Dee
try{
16
output
564
1
2
3
4
/**
*@author: candidjava
*@description: FileOutputStream example program for
getFD()() in JAVA
**/
5
6
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
9
10 public class FileOutputStreamDemo {
11
12
13
FileDescriptor fd = null;
14
15
try {
16
17
18
19
fd = fos.getFD();
20
21
bool = fd.valid();
22
23
24
25
// if an error occurs
26
ex.printStackTrace();
} finally {
27
if (fos != null)
28
fos.close();
29
}
30
31
}
}
32
Output
is file valid? true
1
2
/**
*@author: candidjava
*@description:
**/
import java.io.IOException;
import java.io.FileInputStream;
7
8
9
10
11
int i = 0;
12
char c;
13
try {
14
15
16
17
18
i = fis.read();
19
20
c = (char) i;
21
// prints
22
23
24
25
ex.printStackTrace();
26
} finally {
27
28
29
30
fis.close();
}
31
32
}
}
33
Output
Character read: E
1
2
3
4
/**
*@author: candidjava
*@description: FileOutputStream example program for
write(int b)() in java
**/
5
6
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
9
10 public class FileOutputStreamDemo1 {
11
12
13
14
15
16
char c;
17
try {
18
19
20
21
fos.write(b);
22
23
24
25
26
27
28
29
c = (char) i;
30
// prints
31
System.out.print(c);
32
}
} catch (Exception ex) {
33
34
// if an error occurs
35
ex.printStackTrace();
} finally {
36
37
38 from stream
39
if (fos != null)
40
fos.close();
41
if (fis != null)
42
fis.close();
}
43
}
44
45
Output
B
/**
3
4
5
@author
: "candid"
@date
: 29.10.12
*/
6
7
import java.io.FileInputStream;
import java.io.IOException;
9
10 public class FISDemo {
11
12
13
14
15
16
17
18
available = fis.available();
19
char c = (char) i;
20
System.out.print("Available :" +
21 available);
System.out.println(" Read :" + c);
22
23
24
}
} catch (Exception e) {
e.printStackTrace();
25
} finally {
26
if (fis != null) {
27
fis.close();
28
}
}
29
}
30
31
Output
Available :5 Read :K
Available :4 Read :A
Available :3 Read :R
Available :2 Read :T
Available :1 Read :H
Available :0 Read :I
/**
3
4
5
author
: "candid"
date
: 21.11.12
*/
//java code
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12
13
14
15
InputStream is = null;
16
17
int i = 0;
18
char c;
19
try {
is = new
FileInputStream("F:/karthi/BIStreamSkip/karthi.txt");//
21 karthi.txt
20
// content:karthi
22
23
24
c = (char) i;
25
fis.skip(3);
26
27
28
} catch (IOException e) {
29
e.printStackTrace();
30
} finally {
31
if (is != null)
32
is.close();
33
if (fis != null)
34
fis.close();
}
35
36
}
37
38
Output
Character read: k
Character read: h
/**
* @author: candidjava
*/
5
6
7
8
9
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
10
12
13
14
15 stream
16
17
iStream = new
FileInputStream("c:/test.txt");
// input stream converted to buffered input
18 stream
19
20
21
22
23 bis.read());
24
25
26 bis.read());
27
System.out.println("reset() invoked");
28
// reset is called
bis.reset();
29
30
31 bis.read());
32
33
34
e.printStackTrace();
35
} finally {
36
37
39
iStream.close();
40
if (bis != null)
41
bis.close();
42
}
43
}
}
Output
Char : A
Char : B
Char : C
Char : D
reset() invoked
Char : D
Char : E
/**
@author: Candidjava.com
*/
6
7
10 {
11 try{
12 for(int i=0;i<11;i++)
13
14
15
16
17
18
19
20
{
System.out.println(i);
Thread.sleep(1000); //waiting for one second
}
}
catch(Exception e){}
}
public static void main(String a[])
{
25
26
27
28
29
for(int j=11;j<21;j++)
{
System.out.println(j);
Thread.sleep(1000);
}
30
31
32
}
catch(Exception e){}
}
33 }
34
output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Java Program used to get the pathname of the file using getPath() method
Example Program
?
package service1;
2
3
import java.io.File;
4
5
6
7
8
9
10
File f = null;
String v;
boolean bool = false;
11
12
try {
// create new file
13
f = new File("test.txt");
14
15
16
v = f.getPath();
17
18
19
bool = f.exists();
20
21
// if file exists
22
if (bool) {
23
// prints
24
25
26
} catch (Exception e) {
// if any error occurs
27
e.printStackTrace();
28
29
30
}
31
32
33
Output
pathname: test.txt
Description
The java.io.File.getPath() method converts the abstract pathname into pathname string. To separate the names in the name sequence the
resulting string uses the default name-separator character.
Declaration
Following is the declaration for java.io.File.getPath() method:
public String getPath()
Parameters
Not Applicable.
Return Value
The method returns pathname string form of this abstract pathname.
Exception
Not Applicable.