Java getting exception.printStackTrace as a string

In cases like when I simply want to make a System.out.println or similar with some details of a exception then the following static helper function is very nice as it takes the exception (uses printStackTrace) and returns a string with the contents of it.

public static String getStackTrace(Exception e){
	StringWriter stringWriter = new StringWriter();
	PrintWriter printWrtier = new PrintWriter(stringWriter);
	e.printStackTrace(printWrtier);
	return stringWriter.toString();
}

PHP5: Quick on exceptions

Very quick (&dirty):

1
2
3
4
5
6
7
8
try{
	doStuff();
}
catch (Exception $e){
	echo 'Error on line '. $e->getLine().' in '. $e->getFile() . $e->getMessage();
	//Or if you are working inside an object, you could use.
	echo 'Error on line '.$this->getLine().' in '.$this->getFile() . $e->getMessage();
}

Now to catch a specific kind of exception (in this case CustomException), and say woups, but to re-throw all other Exceptions.

1
2
3
4
5
6
7
8
9
10
11
try{
	doStuffThatCanGiveCustomException();
}
catch (Exception $e){
	//echo get_class($e) . "<br/>";
	if (get_class($e) == "CustomException" && $e->getMessage() === "My custom exception message."){
		echo "woups";
	}
	else
		throw $e;
}

To throw a custom exception:

 throw new Exception('My exception message');

For more informaion about this please check out the php manual